lundi 30 septembre 2019

How to define static member variable from class template with specialization?

OK I have this code:

// default implementation just uses a mutex to serialize access
template <typename T, typename=void>
struct kernport {
    static const bool atomic = false;

    // constructor
    kernport(T value=T()) {
        set(value);
    }

    // get/set value
    T    get()         const { std::unique_lock<std::mutex> lock(lock_); return value_;  }
    void set(const T& value) { std::unique_lock<std::mutex> lock(lock_); value_ = value; }

private:
    mutable std::mutex lock_;
    T value_;
};


// specialization if std::atomic<T> exists
template <typename T>
struct kernport<T, void_type<decltype(std::atomic<T>())>> {
    static const bool atomic = true;

    // constructor
    kernport(T value=T()) {
        set(value);
    }

    // query port value
       T get() const         { return value_.load(std::memory_order_acquire);  }
    void set(const T& value) { value_.store(value, std::memory_order_release); }

private:
    std::atomic<T> value_;
};

If I try to check kernport<bool>::atomic, I get the dreaded undefined reference. OK, so I need to define the member outside of the class:

template <typename T> const bool kernport<T>::atomic;

Unfortunately, doing that, I get:

inc/skunk/dataflow/kernel.h:472:47: error: template definition of non-template ‘const bool sk::kernport::atomic’ template const bool kernport::atomic;

And for the life of me I can find the write syntax. How do I write this?

Create a doubly-linked list using the hierarchical structure with student struct with Big 5 notation

Homework Problem: Create a doubly-linked list using the hierarchical structure with student struct with Big 5 notation. Make sure to include the classes in the user defined class DLL: the big 5, MergeSort, additional helper functions to assist with MergeSort.

I'm trying to put together the big five, mergeSort, and additional helper function(s) to assist with MergeSort in a dynamically allocated doubly linked list with header. Also I'm using a student struct with variables of id, name, email, and gpa.

I've been trying to figure out which variables to use when implementing the code.

#ifndef MERGEDLL_H_
#define MERGEDLL_H_
#include <iostream>
using namespace std;

struct llist{
    int size;
    litemLL *first;
    litemLL *last;
};

struct litemLL{
    llist *origin;
    litemLL *next;
    litemLL *prev;
    record *data;
};

class record{
    int id;
    string name;
    string email;
    double gpa;
};

class mergeDLL{


public:
    mergeDLL(); // constructor
    ~mergeDLL(); // deconstructor
    mergeDLL(mergeDLL&& move); // move constructor
    mergeDLL& operator=(const mergeDLL& copy); // copy assignment
    mergeDLL& operator=(mergeDLL&& move); // move assignment

    friend ostream& operator<<(ostream& os,mergeDLL dll);
};

#endif

De-duplication engine using any language

Create a de-duplication engine that acts as a file storage, retrieval, and handling system. It must take some files as inputs, take data from it in chunks of 8 byte size and store it in some efficient data structure of our choice. The data structure should be robust and must not store duplicate chunks. Instead, it has to make a reference to the original chunk that is repeated.

What would be the most efficient solution to this?

I have a feeling we can use maps to solve it but please give your opinion.

error C2131: expression did not evaluate to a constant

When i run the program in codeblocks it works fine. but when i submitted it in codeforces it shows the error. why? i saw some solutions for one dimensional arrays. but what about multidimensional arrays? how to take variable length for multidimensional arrays?

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int main()
{
  int h,w;
  cin>>h>>w;
  int hi[h],wi[w],arr[h][w];
  memset(arr,0,sizeof(arr));
  long long int result=1;
  for(int i=0;i<h;i++)cin>>hi[i];
  for(int i=0;i<w;i++)cin>>wi[i];
  for(int i=0;i<h;i++){
    for(int j=0;j<=hi[i];j++){
      if(j!=w)arr[i][j]=1;
    }
  }
  for(int i=0;i<w;i++){
    for(int j=0;j<=wi[i];j++){
      if(j!=h)arr[j][i]=1;
    }
  }
  for(int i=0;i<h;i++){
    for(int j=0;j<w;j++){
      //cout<< arr[i][j]<<" ";
      if(arr[i][j]==0){
          result*=2;
      }
    }
    //cout<<endl;
  }
  if(result==1)result=0;
  printf("%lld\n",result%1000000007);
  return 0;
}

Which one is more efficient the method std::basic_string::append or the operator '+'?

Which one is more efficient in avoiding unnecessary copy the append method or the Operator + in C++11?

std::string salute = "Hello";
std::string message = salute.append("Namaste");

OR

std::string salute = "Hello";
std::string message = salute + "Namaste";

Operator + allocates a new buffer but it also has R-value reference constructor which avoids the copy of the rvalue. On the contrary append doesn't allocate new buffer(Right?) but doesn't have any overloaded function with R-value reference parameter.

gmake: *** No rule to make target (install cmake on gitbash, do not have makefile)

I d like to install cmake on gitbash (Windows 10) , because I need it o run shiny-server. https://github.com/rstudio/shiny-server/wiki/Building-Shiny-Server-from-Source#what-if-a-sufficiently-recent-version-of-cmake-isnt-available

When I run ./configure , it gives me the following error

*CMake 3.15.2, Copyright 2000-2019 Kitware, Inc. and Contributors
C compiler on this system is: tcc
C++ compiler on this system is: C:\MinGW\bin\g++.exe C:\MinGW\bin\g++.exe
Makefile processor on this system is: gmake
C:\MinGW\bin\g++.exe has setenv
C:\MinGW\bin\g++.exe has unsetenv
C:\MinGW\bin\g++.exe has environ in stdlib.h
C:\MinGW\bin\g++.exe has stl wstring
C:\MinGW\bin\g++.exe has <ext/stdio_filebuf.h>
---------------------------------------------
gmake: *** No rule to make target '/c/Users/../cmake-3.15.2/Source/cmAddCustomCommandCommand.cxx', neededby 'cmAddCustomCommandCommand.o'.  Stop.
---------------------------------------------
Error when bootstrapping CMake:
Problem while running gmake*

I know that the problem originates because I do not have makefile, however gnumake-windows do not possess makefile.

Could you please tell me how I can overcome this issue, or how I can install cmake on windows , or how I can run shiny-server on windows ?

With lots of thanks

How can i extract n elements out of p in a std::vector with X elements

I have a vector with X elements, how can I extract n elements (3 in the example below) out of p (6 in the example) from the vector? Here is how I did it.

vector<int> a;
a.push_back(10);  a.push_back(11);  a.push_back(12);  a.push_back(13);  a.push_back(14);  a.push_back(15);  a.push_back(16);  a.push_back(17);
a.push_back(18);  a.push_back(19);  a.push_back(20);  a.push_back(21);  a.push_back(22);  a.push_back(23);  a.push_back(24);  a.push_back(25);
a.push_back(26);  a.push_back(27); a.push_back(28);  a.push_back(29);   a.push_back(30);  a.push_back(31);  a.push_back(32);  a.push_back(33);
a.push_back(34);  a.push_back(35);

int X = a.size();

// code to extract 3 elements of 6 until the end of the vector
for (int i=0; i< a.size(); i+=6)
  {

        int j = i+10;

        if (i >= a.size())
        {
            break;
        }
        else
        {
            sub_indices.push_back(i);
        }

        if ( (i+1) >= a.size())
        {
            break;
        }
        else
        {
            sub_indices.push_back(i+1);
        }

        if ((i+2) >= a.size())
        {
            break;
        }
        else {
            sub_indices.push_back(i+2);
        }
  }
// display result would output 
10 11 12 (drop three elements) 16 17 18 (drop three elements) 22 23 24  (drop three elements) 28 29 30 (drop three elements) 34 35

I did it like this but can anyone tell me if there is a more efficient way?

dimanche 29 septembre 2019

cannot convert 'double' to 'double*' for argument '2' to 'double calculation(int, double*)'

i send the address of k and the function should receive by its initialized pointer and next i want to use the value of k and calculate but getting that error.

#include<iostream>
using namespace std;

double calculation(int n,double *k){
    //cout<<&k <<endl <<*k <<endl <<k;
    if(n==0)
        return 0;
    if(n==1)
    return *k;
    else
     return *k / (2*n-3)+calculation(n-1,*k);
}

int main(){
    int n;
    double k=10.00;
    cout<<"Battery amount: " <<endl;
    cin>>n;
    double distance_covered= calculation(n, &k);
    cout<<"The car has moved: " <<distance_covered;
}

Why char array is not printing value?

I am simply trying to print char array after copying some data into it. But cout does not print anything. What is wrong with below code?

Thank you for your help.

int main() {
    char addr[6];
    int id = 2;
    short port = 1;
    memcpy(&addr[0], &id, sizeof(int));
    memcpy(&addr[4], &port, sizeof(short));

    cout << "addres:" << addr << endl;
    return 0;
}

Is it possible for libcurl to return a CURLE_ABORTED_BY_CALLBACK by itself?

CURLCode code = curl_easy_perform(curl);

If we don't return a non-zero value on curl callback, for example CURLOPT_XFERINFOFUNCTION always return zero, and is the curl_easy_perform call possible return CURLE_ABORTED_BY_CALLBACK from internal?

C++: references and smart pointers - is there such a thing as a smart reference?

Initially references have been introduced to C++ to hide the ugly pointer syntax much like many modern program languages do.

Now, with smart pointers it looks to me like we have to (again) explicitly use ptr->element or *ptr.element instead of just reference.element.

Is this the price we have to pay for having explicit control over ownership, i.e. being able to either keep it or move it on?

Or do I miss something...?

Why compiler takes extra bytes during virtual inheritance? [duplicate]

This question already has an answer here:

While I was learning about virtual inheritance in C++. In the following program, the size of the derived class is 16 extra bytes than that of the base class, however this amount varies for different data types used in base class. How compiler uses those extra bytes? How is this behaviour defined in C++?

#include<iostream>

using namespace std; 

class base {
    double arr[10];  
}; 

class b1: virtual public base { }; 

class b2: virtual public base { }; 

class derived: public b1, public b2 {}; 

int main(void) 
{ 
    cout<<sizeof(derived)<<" "<<sizeof(base); 
    return 0; 
} 

Output:

96 80

Can variable name be same as Function name in C++?

In the above code lis is an array as well as a function name with same return type (int), I didn't get any error, Can anybody explain what is happening in the background? Why is the compiler not showing an error?

int lis( int arr[], int n )  
{  

int lis[n]; 
lis[0] = 1;    
for (int i = 1; i < n; i++ )  
{ 
    lis[i] = 1; 
    for (int j = 0; j < i; j++ )   
        if ( arr[i] > arr[j] && lis[i] < lis[j] + 1)  
            lis[i] = lis[j] + 1;  
} 

samedi 28 septembre 2019

cin.fail not working when numbers and letters entered

I am working on a simple data validation as part of inputting numbers to an array. Right now it is working for the most part with the exception of one case - when I enter a number followed by a letter, the error message that I created it thrown, but the number is still entered into the array. Further confusing me is that it is functioning as intended when I compile the program in Xcode, but the issue I'm describing only shows up when I compile the program with g++. Any thoughts would be very appreciated. Here is my function which I think is giving me the issue.

float getInput()
{
    float input;
    std::cin >> input;
    if (std::cin.fail())
    {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "type char/str not allowed, enter int" << '\n';
        return getInput();
    }
    else
        return input;
}

TCP non blocking socket packet loss

It looks like the send() func in this case is too much faster than recv() and recv() never reach 262144-bytes I don't wanna use blocking sockets as there are many messages that have to be processed by the MsgPoc callback, any idea on how to fix this

// peer 1
char buff[262144]; // 265 kb

LRESULT CALLBACK MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
        //...
    case WM_SOCKET:     // #define WM_SOCKET (WM_USER + 1)
        switch (WSAGETSELECTEVENT(lParam))
        {
        case FD_READ:
        {
            nBytes += recv(sock, buff, 262144, 0); // always receiving 5840 bytes max
            fwrite(buff, 1, 262144, file);            
            break;
        }
        //...
    }
    return 0;
}

// peer 2 sends packets from the main loop
while (GetMessage(&msg, nullptr, 0, 0))
{
    TanslateMessage(&msg);
    DispatchMessage(&msg);

    fread(buff, 1, 262144, file);
    nBytes += send(sock, buff, 262144, 0);
}

Making sense of nested lambda expression

My question pertains to the following nested lambda expression, provided as an example under Lambda expressions

// generic lambda, operator() is a template with one parameter
auto vglambda = [](auto printer) {
    return [=](auto&&... ts) // generic lambda, ts is a parameter pack
    { 
        printer(std::forward<decltype(ts)>(ts)...);
        return [=] { printer(ts...); }; // nullary lambda (takes no parameters)
    };
};
auto p = vglambda([](auto v1, auto v2, auto v3) { std::cout << v1 << v2 << v3; });
auto q = p(1, 'a', 3.14); // outputs 1a3.14
q();                      // outputs 1a3.14

The following is the way I interpret the above expression:

In the expression

auto p = vglambda([](auto v1, auto v2, auto v3) { std::cout << v1 << v2 << v3; });

the closure object vglambda is initialized with the closure object printer whose type corresponds to the lambda expression

[](auto v1, auto v2, auto v3) { std::cout << v1 << v2 << v3; }

Inside printer, the nested (anonymous) lambda expression

return [=](auto&&... ts){}

captures printer by copy and its parameter pack as rvalue reference.

Inside the body of the (anonymous) lambda expression, the expression

printer(std::forward<decltype(ts)>(ts)...);

forwards the parameter pack to printer [in what essentially appears to be an invocation of printer using operator ()]

In the final expression inside the body of the (anonymous) lambda expression, the (anonymous) nullary lambda expression appears to capture the printer closure object from the enclosing scope by copy, along with the parameter pack, and invokes the printer closure object with its forwarded parameter pack.

return [=] { printer(ts...); };

Now, it is very evident that I am not getting something right here. Essentially, why are two distinct lines of invoking the printer closure object provided within the body of the (anonymous) lambda expression, one without the (anonymous) nullary lambda expression, and one within?

Can any of the experts throw more light?

Avoid copying in returning current object

The following code implements a methods that either returns a copy of its corresponding object or creates a new object and returns it based on the value of cond. Ideally, I wish to change it in a way that if cond is true, the method returns it's object not a copy of it.

#include <iostream>
#include <vector>
class Base {
protected:
std::vector<int> p_;
public:
    Base(std::vector<int> p) : p_(p.begin(), p.end()) {}
    Base getObj() const {
        if (cond) {
            return *this; // Even if cond is true, I'm copying here. This is what I wish to change.
        } else {
            std::vector<int> p1 = {...};
            return Base(p1);
        }
    }
};



int main() {
    std::vector<int> v = {2, 4, 5};
    std::vector<Base> objects;
    Base b(v);
    objects.emplace_back(b.getObj());
}

More Details

I'm flexible to change the return type of getObj to reference or pointer. Nonetheless, I cannot change this vector that holds the output: std::vector<Base> objects;

Finding two integers that sum to a target integer

This is a problem that from an algorithmic challenges book that I have been struggling with for the past couple days.

Given an integer N, find two positive integers A and B such that A + B = N and neither A nor B contain a "0" in them. For example, if N = 12, you would be able to return (A, B) = (6, 6), (5, 7), (4, 8), (3, 9), etc but you wouldn't be able to return (10, 2) or (2, 10).

I have been struggling to solve this problem for several days, and I cannot understand a solution that someone else gave me. I was wondering whether someone would either be able to make sense of the solution and help me implement it, or if they are able to come up with an (efficient) solution of their own.

Here is the solution that I was told:

"Consider the digits of N one-by-one, starting from the least significant digit. If you encounter the number 0, add 10 to the digit, and add 9 to all zeroes between this digit and the next non-zero digit, and subtract 1 from this non-zero digit. Of course, this non-zero digit might become zero, and if this is the case, we need to do the same thing, starting from this index. Also, you should do the same thing if you encounter a 1 (as long as this 1 is not the most significant digit). Afterwards, process every digit, except perhaps, for the most significant one will be in range [2, 11], a partition will become obvious.

As an example, suppose we have 2003. Then, we process it in reverse to get 3002 -> 3 | 10 | 9 | 1, so we have the digits 3, 10, 9, and 1. From here, we can can easily make a partition, for example, 1|5|4 and |2|5|5|1 (the first number consists of A[i]/2), and we can see that 451 + 1552 = 2003."


I'm really confused about how to implement what they're talking about. I've tried my best for the past several hours with no luck. I was hoping someone here would either know a good solution to solve this problem, or if they are able to make sense of the solution provided above (either one is fine). Here is what I've tried to implement in C++; however, it does not actually work for all numbers (e.g. it breaks for N = 12, N = 13, and several other examples).

int main() {

    int N = 2003;
    vector<int> reverse_of_int;

    while (N > 0) {
        reverse_of_int.push_back(N % 10);
        N /= 10;
    }

    for (int i = 0; i < reverse_of_int.size(); i++) {
        if (reverse_of_int[i] == 0 || reverse_of_int[i] == 1) {
            reverse_of_int[i] += 10;
            i++;
            while (i < reverse_of_int.size() && reverse_of_int[i] == 0) {
                reverse_of_int[i] += 9;
                i++;
            }
            if (i < reverse_of_int.size()) {
                reverse_of_int[i] -= 1;
            }
        }

        if ((reverse_of_int[i] == 0 || reverse_of_int[i] == 1) && i != reverse_of_int.size() - 1) {
            i--;
        }
    }

    vector<int> A;
    vector<int> B;


    for (int i = reverse_of_int.size() - 1; i >= 0; i--) {
        A.push_back(reverse_of_int[i]/2);
        B.push_back(reverse_of_int[i] - A[reverse_of_int.size() - 1 - i]);
    }


    cout << "ANSWER for N =  " << copyN << endl;
    bool flag = false;
    F0R(i, A.size()) {
        if (A[i] == 0 && i != 0) flag = true;
        cout << A[i];
    }
    cout << endl;
    F0R(i, B.size()) {
        if (B[i] == 0 && i != 0) flag = true;
        cout << B[i];
    }
    cout << endl;

    return 0;
}

variable cannot be implicitly captured in a lambda with no capture-default specified using a switch statement

I am trying to convert a name to a number. my problem is that as I try to do a simple a=a+1 in a switch statement I get the error message "variable 'a' cannot be implicitly captured in a lambda with no capture-default specified"

looking around here for the same error message I see that I should use [], [=] or [&]. my problem seems more how and where to do so. if I go [](int a=0){}; where I initialize the variable then my message is " error: use of undeclared identifier 'a'"

here is the code with my problem

#include <jni.h>
#include <string>
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;

static int nameToNumber(string fn, string ln)
{
    string nameOne = fn;
    string nameTwo = ln;
    [](int a=0){};
    int b = 0;
    int num = 0;

    for_each(nameOne.begin(), nameOne.end(), [](char &c )
    {
        c=::toupper(c);

        switch (c){

            case 'A':
            case 'J':
            case 'S': a=a+1;
                break;
            case 'B':
            case 'K':
            case 'T': a=a+2;
                break;
            case 'C':
            case 'L':
            case 'U': a=a+3;
                break;
            case 'D':
            case 'M':
            case 'V': a=a+4;
                break;
            case 'E':
            case 'N':
            case 'W': a=a+5;
                break;
            case 'F':
            case 'O':
            case 'X': a=a+6;
                break;
            case 'G':
            case 'P':
            case 'Y': a=a+7;
                break;
            case 'H':
            case 'Q':
            case 'Z': a=a+8;
                break;
            case 'I':
            case 'R': a=a+9;
                break;
            default: a=a+0;
        }
    });


    for_each(nameTwo.begin(), nameTwo.end(), [](char &c)
    {


        c=::toupper(c);
        switch (c){

            case 'A':
            case 'J':
            case 'S': b=b+1;
                break;
            case 'B':
            case 'K':
            case 'T': b=b+2;
                break;
            case 'C':
            case 'L':
            case 'U': b=b+3;
                break;
            case 'D':
            case 'M':
            case 'V': b=b+4;
                break;
            case 'E':
            case 'N':
            case 'W': b=b+5;
                break;
            case 'F':
            case 'O':
            case 'X': b=b+6;
                break;
            case 'G':
            case 'P':
            case 'Y': b=b+7;
                break;
            case 'H':
            case 'Q':
            case 'Z': b=b+8;
                break;
            case 'I':
            case 'R': b=b+9;
        }
    });

num = a + b;
if ((num > 9) && (num != 11) && (num != 22) && (num != 33))
{
//add both digits together to get a single digit
a=0;
b=0;

a = num / 10; //get first digit
b = num % 10; //get second digit
num = a + b; //add them together
}
return num;
}

and here is where I call it

extern "C" JNIEXPORT jstring JNICALL
Java_com_sezju_namenumerology_MainActivity_transformInfo(
        JNIEnv *env,
        jobject /* this */,
        jstring fName,
        jstring lName,
        jint age) {
int luckynum = nameToNumber(jstringToString(env, fName), jstringToString(env, lName));
string message = jstringToString(env, fName) + " " + jstringToString(env, lName) + ".\n";
message += "You are " + decToHexa((int)age)+ " years old in hexadecimal. \n";
message += "Your number is " + std::to_string(luckynum) + " \n";
return env->NewStringUTF(message.c_str());

my expected result would be, for a name entered to have a result of a single digit, or 11, 22, or33.

std::thread class member variable with unexpected behaviour

new to stackoverflow. I usually search and find all answers to my questions but for my current problem I couldn't find any help.
I introduced a std::thread member variable inside my Request class, which is supposed to work a routine in the background. The routine is sending a request, collecting the data and waiting a short amount of time before repeating. After the first iteration of the routine, other member variables of the class object change unexpectedly.

I had this request routine working before without the std::thread member variable. When I added the std::thread member variable, I had to delete the copy and the copy assignment member functions, because threads can't be copied. Even when commenting the sendRequest function and just sleeping, the request object gets modified. I've tried various different approaches of defining and initializing the std::thread class member.

    class Request { 
    public:
        Request() = default;
        Request(/*args*/);
        Request(const Request&) = delete;
        Request& operator=(const Request&) = delete;
        Request(Request&&) = default;
        Request& operator=(Request&&) = default;
        ~Request();
        bool active = true;
    private:
        void start();
        void routine();
        void sendRequest();
        std::thread requestRoutine;
        std::chrono::seconds sleepinterval;
        //std::queue<std::vector<std::pair<Query, json::value>>> responseQueue;
    }

    Request::Request(/*args*/)
        : requestRoutine()
    {
        /*init member variables*/
        start();
    }

    void Request::start()
    {
        requestRoutine = std::thread(&Request::routine, this);
        requestRoutine.detach();
    }

    void Request::routine()
    {
        while (this->active) {
            sendRequest();
            std::this_thread::sleep_for(sleepinterval);
        }
    }

I reduced the class to the important member functions and variables. If you are interested, I am using the cpprestsdk to send a HTTP request and i am receiving a HTTP response with a JSON object in the body. The most import includes for this file are the following:

#pragma once
#include <iostream>
#include <thread>
#include "boost/date_time/posix_time/posix_time.hpp"
#include "boost/date_time/gregorian/gregorian_types.hpp"
#include <cpprest/http_listener.h>
#include <cpprest/http_client.h>
#include <cpprest/json.h>
#include <cpprest/filestream.h>

Any help and advice is much appreciated.
Thank you!

What is the correct way to call a move constructors on the derived class?

I'm writing a piece of code that inherits from a user provided class (not for polymorphism reasons). I need to write an explicit move constructor/assignment for it because I store pointers to some internal data of my class. I don't know how to call move constructor well.

Example:

template <typename UserType>
class my_class : UserType  {
  other_data data;
 public:
  my_class(my_class&& x) UserType(/*...*/), data(std::move(x.data)) {}
};

Options:

  • I can call move(x) => but then it's use after move.
  • I can do some static_cast<UserType&&>(x) - but that's quite unusual.

What's a good solution here?

Even though my sample output matches with expected output, sample test cases aren't passed

I submitted the code for a competitive programming hiring challenge and even though my sample test cases are same as expected my sample test cases aren't passed, Please help me.

I've already tried using \t , before or after to exactly match the expected output, even though the code may be wrong, at-least sample test cases should be passed

#include<iostream>

int main(){
    int a[2000],z,T,N;

    std::cin >> T;

      while(T--) {

    std::cin >> N;

    for(int i=0;i<N;i++) {
        if(i==0||i==1) {
            a[i] = 1;
            }
        if(i==2) {
            a[i] = a[i-1] + a[i-2];
            z = a[i];
            }
        if(i>2) {
            if(i%2!= 0) {
                a[i] = z;
            }
            else{
                a[i] = a[i-1] + a[i-2];
            }
        }
    }
    for(int i=0;i<N;i++) {
    std:: cout << a[i] << "\t" ;    
    }
    std:: cout << "\n";
    }
     return 0;
     }

Expected and actual results look almost same as mentioned in screenshot, sample test cases should be passed...

enter image description here

vendredi 27 septembre 2019

Error in the declaration of max heap in c++

what is the error in this declaration of max heap

priority_queue,vector>,[](const pair&a,const pair&b) {return a.second < b.second;}>max_Heap; error message : template argument 3 is invalid

How to use std::max with a custom comparator in C++11?

I have a vector of Hill structs and want to find the one with the heighest height. Here's my code:

#include <vector>
#include <algorithm>
#include <assert.h>
struct Hill {
    int height;
    int changed;
};
int main() {
    std::vector<Hill> hills(100);
    hills[0].height = 100;
    hills[1].height = 150;
    auto byHeight = [&](const Hill& a, const Hill& b) {
        return a.height < b.height;
    };
    Hill hill = std::max(hills.begin(), hills.end(), byHeight);
    assert(hill.height == 150);
}

But it fails to compile:

mcve.cpp:15:10: error: no viable conversion from 'const
      std::__1::__wrap_iter<Hill *>' to 'Hill'
    Hill hill = std::max(hills.begin(), hills.end(), byHeight);
         ^      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
mcve.cpp:4:8: note: candidate constructor (the implicit copy constructor) not
      viable: no known conversion from 'const std::__1::__wrap_iter<Hill *>' to
      'const Hill &' for 1st argument
struct Hill {
       ^
mcve.cpp:4:8: note: candidate constructor (the implicit move constructor) not
      viable: no known conversion from 'const std::__1::__wrap_iter<Hill *>' to
      'Hill &&' for 1st argument
struct Hill {
       ^
In file included from mcve.cpp:1:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/vector:270:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/__bit_reference:15:
/Library/Developer/CommandLineTools/usr/include/c++/v1/algorithm:2627:12: error: 
      no matching function for call to object of type '(lambda at
      mcve.cpp:12:21)'
    return __comp(__a, __b) ? __b : __a;
           ^~~~~~
mcve.cpp:15:22: note: in instantiation of function template specialization
      'std::__1::max<std::__1::__wrap_iter<Hill *>, (lambda at mcve.cpp:12:21)>'
      requested here
    Hill hill = std::max(hills.begin(), hills.end(), byHeight);
                     ^
mcve.cpp:12:21: note: candidate function not viable: no known conversion from
      'const std::__1::__wrap_iter<Hill *>' to 'const Hill' for 1st argument
    auto byHeight = [&](const Hill& a, const Hill& b) {
                    ^
2 errors generated.

How do I fix it?

Looping on table and showing a specific subclass member C++

I want to do a for loop on the table tab. In each iteration, I would like to check the type of the current element.

If it is an instance of B class then I print b, c otherwise.

Thank you for your help.

class A {} 
class B: public A {
  private int b; 
  // constructor + getter + setter 
} 
class C: public A { 
  private int c; 
  // constructor + getter + setter 
} 
// in the main 
B obj1(val1); 
C obj2(val2); 
A tab [] = {obj1, obj2}; 

Using user defined literals at run runtime

I am trying to use user defined literals at runtime.

Instead of hard coding the literal at compile time, I would like to specify the value at runtime.

I created this, but now cannot progress.

#include <cmath>
#include <iostream>

class Degrees
{
    double degree_;

public:

    explicit Degrees(long double degree) : degree_(degree) {}

    double GetValue() const { return degree_; };
};

Degrees operator "" _deg(long double degree)
{
    // Returns radians
    return Degrees(degree * 3.14159265358979323846264L / 180);
}

int main(int argc, const char * argv[])
{
    long double angle;
    std::cin >> angle;

    Degrees degrees(angle);

    //degrees = 3.1_deg;

    std::cout << degrees.GetValue() << "\n";
    return 0;
}

Is there a purpose to this _com_ptr_t move assignment?

So we have this code

_com_ptr_t& operator=(_com_ptr_t&& cp) throw()
{
    if (m_pInterface != cp.m_pInterface) {
        Interface* pOldInterface = m_pInterface;

        m_pInterface = cp.m_pInterface;
        cp.m_pInterface = nullptr;

        if (pOldInterface != nullptr) {
            pOldInterface->Release();
        }
    }

    return *this;
}

The pOldInterface is Release()d on move assignment. Why are move assignment/constructor operations not implemented as swaps which lets the Release() occur naturally on moved object's destruct or just use the nullptr assignment or Release() to manually trigger it early?

I always implement move constructors as swap operations. Is this bad practice?

My code would be

_com_ptr_t& operator=(_com_ptr_t&& cp) throw()
{
    if (m_pInterface != cp.m_pInterface) {
        Interface* pOldInterface = m_pInterface;
        m_pInterface = cp.m_pInterface;
        cp.m_pInterface = pOldInterface;
        // or just std::swap(m_pInterface, cp.m_pInterface);
    }
    return *this;
}

Is there a reasoning behind MS _com_ptr_t choice? This question also applies to any move assignment/constructor so this context is more/less relevant. It's all about whether we release data or we swap it?

Removing element from std::map

This code is leading to unexpected behavior.

Ideally, I should get 1000 for all the values (key-value) but sometimes it gives me 0 for the next key value after deletion.

For ex: Initially map ['a', 0] ['b',0] ['c',0] ['d',0] ['e',0] ['f',0]

After deletion ['a', 1000] ['b',1000] ['d',0] ['e',1000] ['f',1000]

std::map<char, uint_32> pool;

void remove_entry(char key) {
     std::map<char, int>::iterator it = pool.find(key);

     pool.erase(it)
}

std::map<char, int>& get_pool() {
     return pool;
}

void process() {

     for (auto& kv : get_pool()) {

          if (kv.first == 'c') {
              remove_entry(kv.first);

              continue;
          }

          kv.second = 1000;
     }

}

Any help is appreciated. Thanks in advance.

C++ enumeration and

Ive suck countless hours into this program and to no avail I find the enumeration not working on my last day. My program is below. It deals with Dual Stacks and has lots of comments to help read through. The enumeration is not working properly because when I 'pop' off the stack then its not popping the right enumeration/name. Also, the time is in HH:MM:SS and it needs ot be in SS:Milliseconds. Clock format is not a huge deal, so if anything Id like to know WHY the enum isnt working, and fixes for it. Any other help would be appreciated.

#include <iostream>
#include <iomanip> 
#include <ctime>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string>
#include <chrono>
#include <thread>
#include <fstream>

using namespace std;
const int MAX = 20;
typedef std::chrono::high_resolution_clock Clock;
int seed;
int upper;
int lower;
float randNum;
float randNumArr;
float randNumTie;
float randNumStar;
int dagabacount = 0;
int numberArrivals;
clock_t start;
double duration;
int fixedvehicles = 0;
enum alphabet {A =0,B, C, D, E, F, G, H,I, J, K, 
L , M , N , O , P ,Q ,R, S, T , U, V , W , X , Y , Z};
alphabet alphS;
alphabet alphT;
string TieName;
string StarName;
//function for randomly generating number for delay time for ties
int randTieDelay(){
    randNumTie = float(rand()) / (float(RAND_MAX) + 1.0);
          if(randNumTie < 0.333){
             return 2;
          }
          else if(.333 <= randNumTie < .66){
              return 4;
          }
          else{
             return 6;
          }
}

//function for randomly generating number for delay time for stars
int randStarDelay(){
    randNumStar = float(rand()) / (float(RAND_MAX) + 1.0);
          if(randNumStar < 0.25){
             return 3;
          }
          else if(.25 <= randNumStar < .50){
              return 4;
          }
          else if(.50 <= randNumStar < .75){
              return 7;
          }
          else{
             return 10;
          }
}

//struct for vmr
struct vmr{
    char type;
    string name;
    int repairTime;
};

vmr item;

//declaring dualstack
class repairStack
{
    private:
        int topT;
        int topS;
        vmr ele[MAX];

    public:
        repairStack();
        void pushTie   (struct  vmr);
        void pushStar  (struct  vmr);
        int  popTie    (vmr *item); 
        int  popStar   (vmr *item);
}; 

//initializing dualstack
repairStack::repairStack()
{
    topT = -1;
    topS = MAX;
}

//pushing to tiestack
void repairStack::pushTie( vmr v)
{
    if( topS == topT + 1 )
    {
        cout<<"\nStack Overflow Tie Stack: Pushing to Dagaba"<<endl;
        if(dagabacount == 6){
            return;
        }
        else{
        cout<< "Total ships sent to Dagaba: " << dagabacount <<endl;
        dagabacount++;

        return;}
    }
    topT++;
    ele[topT] = v;
}

//pushing to starstack
void repairStack::pushStar( vmr v)
{
    if( topS == topT + 1 )
    {
        cout<<"\nStack Overflow on Star Stack: Pushing to Dagaba" <<endl;
         if(dagabacount == 6){
            return;
        }
        else{
        cout<< "Total ships sent to Dagaba: " << dagabacount <<endl;
        dagabacount++;

        return;}
    }
    topS--;
    ele[topS] = v;
}

//popping to tiestack,checking for underflow, using system clock to start time of repair
//uses chrono clock and this_thread::sleep_for(); that is defined in c++11
int repairStack::popTie( vmr *item )
{
    if( topT == -1 )
    {
        //cout<<"\nStack Underflow tStack";
        return -1;
    }

    using std::chrono::system_clock;
    std::time_t tt = system_clock::to_time_t (system_clock::now());
    struct std::tm * ptm = std::localtime(&tt);
    cout << "\nName: Tie" << item->name <<endl;
    std::cout << "Start time: " << std::put_time(ptm,"%X") << '\n';
    int delay = randTieDelay();
    std::this_thread::sleep_for (std::chrono::seconds(delay));
    cout << "Type: Tie Fighter" << endl;
    cout << "Repair Time: " << delay << endl;

    *item = ele[topT--];
    return 0;
}

//popping to starstack, checking for underflow, using system clock to start time of repair
//uses chrono clock and this_thread::sleep_for(); that is defined in c++11
int repairStack::popStar( vmr *item )
{
    if( topS == MAX )
    {
        //cout<<"\nStack Underflow sStack";
        return -1;
    }

    using std::chrono::system_clock;
    std::time_t tt = system_clock::to_time_t (system_clock::now());
    struct std::tm * ptm = std::localtime(&tt);
    cout << "\nName: Star"<< item->name <<endl;
    std::cout << "Start time: " << std::put_time(ptm,"%X") << '\n';
    int delay = randStarDelay();
    std::this_thread::sleep_for (std::chrono::seconds(delay));
    cout << "Type: Star Destroyer" << endl;
    cout << "Repair Time: " << delay << endl;

    *item = ele[topS++];
    return 0;
}

//randomly generating how many arrivals come in each iteration
int getNumArrivals(){
        randNumArr = float(rand()) / (float(RAND_MAX) + 1.0);
          if(randNumArr < 0.25){
             return 1;
          }
          else if(.25 <= randNumArr < .50){
              return 2;
          }
          else if(.50 <= randNumArr < .75){
              return 3;
          }
          else{
             return 4;
          }
}

int main()
{ 
    //asking user for bounds
    cout << "Please give seed value: ";
    cin >> seed;
    cout << "Please give lower bound of stack: ";
    cin >> lower;
    cout << "Please give upper bound of stack: ";
    cin >> upper;
    cout << "\n";
    srand(seed);
    //initalizing stack 's'
    repairStack s = repairStack();

    //initializing clock and entire duration of program
    start = clock();
    duration = ( clock() - start ) / (double) CLOCKS_PER_SEC;

    //while rejected vehicles is under 5
    while(dagabacount < 5){

        //getting numberArrivals either 1,2,3,4
        numberArrivals = getNumArrivals();
        cout << "Number of Arrivals: " << numberArrivals;
            int tfperloop = 0;
            int sdperloop = 0;
        for(int i = 0; i < numberArrivals; i++){

          //getting random number between 0 and 1 to see if its T or S
          randNum = float(rand()) / (float(RAND_MAX) + 1.0);

          //if tie then creates and adds struct and pushes to tie stack
          //gets next enumeration for ties
          if(randNum < 0.75){
            TieName = (char)(alphT + 65);
            struct vmr Tie;
            Tie.type='T';
            Tie.repairTime = 3;
            Tie.name = TieName;
            s.pushTie(Tie);
            int t = (int)alphT;
            t= (t+1)%26;
            alphT = (alphabet)t;
            tfperloop++;
          }

          //if star then creates and adds struct and pushes to star stack
          //gets next enumeration stars
          else{
            StarName = (char)(alphS + 65);
            struct vmr Star;
            Star.type='S';
            Star.repairTime = 7;
            Star.name = StarName;
            s.pushStar(Star);
            int g = (int)alphS;
            g= (g+1)%26;
            alphS = (alphabet)g;
            sdperloop++;
          }
        }
          //cout << "\n# of Tie Fighters in this Arrival: " << tfperloop <<endl;
          //cout << "# of Star Destroyers in this Arrival: " << sdperloop <<endl;

        //fixing star if star stack is not empty, if so, fix a tiefighter if theres one in stack
        //uses chrono clock to get system time at that struct and localtime are libraries within C++ 
        if(s.popStar(&item) == 0){
            cout << "Status: Fixed" << endl;
            using std::chrono::system_clock;
            std::time_t tt = system_clock::to_time_t (system_clock::now());
            struct std::tm * ptm = std::localtime(&tt);
            std::cout << "Finish time: " << std::put_time(ptm,"%X") << endl << endl;
            fixedvehicles++;
            std::this_thread::sleep_for (std::chrono::seconds(2));
        }
        else{
            if(s.popTie(&item) == 0){
                cout << "Status: Fixed" << endl;
                using std::chrono::system_clock;
                std::time_t tt = system_clock::to_time_t (system_clock::now());
                struct std::tm * ptm = std::localtime(&tt);
                std::cout << "Finish time: " << std::put_time(ptm,"%X") << endl << endl;
                fixedvehicles++;
                std::this_thread::sleep_for (std::chrono::seconds(2));
            }
            else{
                cout << "Underflow" << endl;
            }
        }
    }
        //print out some results of the program for user benefit
        cout << "5 Vehicles Sent To Dagaba" << endl;
        cout << "# of Vehicles Serviced: " << fixedvehicles << endl;
        cout << "Average Time of Repair: " << duration / fixedvehicles << endl;

    return 0;
}

Initializing std::shared_ptr with std::make_shared having an std::array as argument

I do not understand why this works fine:

std::array<double, 2> somearray = {0,1};
std::shared_ptr<MyClass> myobj = make_shared<MyClass>(somearray);

But this does not work:

std::shared_ptr<MyClass> myobj = make_shared<MyClass>({0,1});

It says:

too many arguments to function ‘std::shared_ptr< _Tp> std::make_shared(_Args&& ...)
...
candidate expects 1 argument, 0 provided

Can someone clarify why this happens and if there is any way I can fix the second approach without defining an extra variable?

Is there any structure other than if-else to do condition specific action?

Assume I have a class (classBase) interacting with several classes (class1, class2, class3, ...). This class (classBase) does some action based on target variables in other classes. In the code below, a classNComplete can only be true if classN.variable is greater than one (please see the code below).

(Assume that it can enter to the while loop in the first run)

Code in classBase

while (!(class1Complete && class2Complete && ...)) {
  if (class1.variable > 1) {
    /* do something; class1Complete = true; */ } else {
    /* do something; class1Complete = false; */ }

  if (class2.variable > 1) {
    /* do something; class2Complete = true; */ } else {
    /* do something; class2Complete = false; */ }
  ...
}

Since there are lots of classes to check if the variable is greater than 1, I find this code very cumbersome. I am wondering if there is another implementation to this kind of problems.

How to call operator template?

I am feeling a bit confused about how to instantiate this template. I know it is gonna be easier to simply use friend membership to realize what I want, but what if I force to do in this way? I just wanna figure it out. (And btw, I know this template seems meaningless), I just want to make it compile.

#include <iostream>

template <typename T>
inline std::ostream& operator<< (std::ostream& os, const T& date)
{
    os << date.getD() << " " << date.getM() << " " << date.getY() << "\n";
    return os;
}

class Date 
{
private:
    int dd, mm, yy;
public:
    Date(int d, int m, int y) : dd(d), mm(m), yy(y) {}
    int getD() const;
    int getM() const;
    int getY() const;
};

int Date::getD() const {  return dd; }

int Date::getM() const {  return mm; }

int Date::getY() const {  return yy; }

int main(int argc, char const *argv[])
{
    Date dat(1, 2, 2003);
    std::cout << <Date> dat;
    return 0;
}

skipping incompatible libraries in centos 7.5 codeblocks

I've centos 7.5 as workstation VM and tring to compile piece of code using codeblocks. I've problem while compiling :-

g++ -Wall -std=c++11 -g -I/usr/local/include/SDL2 -I/usr/include/GL -c "/opt/projects/codeblocks/graphics pmg/keyboard/keyboard 1/main.cpp" -o obj/Debug/main.o
g++ -L/usr/lib -L/usr/local/lib -o "bin/Debug/keyboard 1" obj/Debug/main.o   -lSDL2 -lSDL2main -lGLEW -lGLU -lGLw -lGL
/usr/bin/ld: skipping incompatible /usr/lib/libGLU.so when searching for -lGLU
/usr/bin/ld: skipping incompatible /usr/lib/libGLw.so when searching for -lGLw
/usr/bin/ld: skipping incompatible /usr/lib/libGL.so when searching for -lGL
/usr/bin/ld: skipping incompatible /usr/lib/libm.so when searching for -lm
/usr/bin/ld: skipping incompatible /usr/lib/libm.a when searching for -lm
/usr/bin/ld: skipping incompatible /usr/lib/libc.so when searching for -lc
/usr/bin/ld: skipping incompatible /usr/lib/libc.a when searching for -lc

I searched in /usr/lib there are both files "/usr/lib/libc.so" & "/usr/lib/libc.a" and "/usr/lib/libm.so" & "/usr/lib/libm.a" and "/usr/lib/libGL.so.1.2.0" & "/usr/lib/libGL.so.1.7.0" installed by different rpms.

output:-

[root@centos75client Debug]# ll /usr/lib/libGL*
lrwxrwxrwx. 1 root root     22 May 29 17:27 /usr/lib/libGLdispatch.so.0 -> libGLdispatch.so.0.0.0
-rwxr-xr-x. 1 root root 341632 Oct 31  2018 /usr/lib/libGLdispatch.so.0.0.0
lrwxrwxrwx. 1 root root     18 Sep 18 10:02 /usr/lib/libGLESv2.so -> libGLESv2.so.2.0.0
lrwxrwxrwx. 1 root root     18 Sep 18 10:02 /usr/lib/libGLESv2.so.2 -> libGLESv2.so.2.0.0
-rwxr-xr-x. 1 root root  65748 Apr 11  2018 /usr/lib/libGLESv2.so.2.0.0
lrwxrwxrwx. 1 root root     17 Sep 18 10:02 /usr/lib/libGLEW.so.1.10 -> libGLEW.so.1.10.0
-rwxr-xr-x. 1 root root 441152 Nov 20  2015 /usr/lib/libGLEW.so.1.10.0
lrwxrwxrwx. 1 root root     14 Sep 18 10:02 /usr/lib/libGL.so -> libGL.so.1.2.0
lrwxrwxrwx. 1 root root     14 Sep 18 10:02 /usr/lib/libGL.so.1 -> libGL.so.1.7.0
-rwxr-xr-x. 1 root root 562228 Apr 11  2018 /usr/lib/libGL.so.1.2.0
-rwxr-xr-x. 1 root root 400772 Oct 31  2018 /usr/lib/libGL.so.1.7.0
lrwxrwxrwx. 1 root root     15 Sep 18 10:02 /usr/lib/libGLU.so -> libGLU.so.1.3.1
lrwxrwxrwx. 1 root root     15 Sep 18 10:02 /usr/lib/libGLU.so.1 -> libGLU.so.1.3.1
-rwxr-xr-x. 1 root root 560272 Jun 11  2014 /usr/lib/libGLU.so.1.3.1
lrwxrwxrwx. 1 root root     15 Sep 18 10:02 /usr/lib/libGLw.so -> libGLw.so.1.0.0
lrwxrwxrwx. 1 root root     15 Sep 18 10:02 /usr/lib/libGLw.so.1 -> libGLw.so.1.0.0
-rwxr-xr-x. 1 root root  21368 Jun 11  2014 /usr/lib/libGLw.so.1.0.0
lrwxrwxrwx. 1 root root     20 May 29 17:27 /usr/lib/libGLX_mesa.so.0 -> libGLX_mesa.so.0.0.0
-rwxr-xr-x. 1 root root 579512 Nov  1  2018 /usr/lib/libGLX_mesa.so.0.0.0
lrwxrwxrwx. 1 root root     15 May 29 17:27 /usr/lib/libGLX.so.0 -> libGLX.so.0.0.0
-rwxr-xr-x. 1 root root  70016 Oct 31  2018 /usr/lib/libGLX.so.0.0.0
lrwxrwxrwx. 1 root root     25 May 29 17:27 /usr/lib/libGLX_system.so.0 -> /usr/lib/libGLX_mesa.so.0

output of locate :-

[root@centos75client Debug]# locate libGL.so | egrep ^/usr | xargs file
/usr/lib/libGL.so:         symbolic link to `libGL.so.1.2.0'
/usr/lib/libGL.so.1:       symbolic link to `libGL.so.1.7.0'
/usr/lib/libGL.so.1.2.0:   ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, BuildID[sha1]=9c9d874bcd64c89f0baea60a7878bd5d10942844, stripped
/usr/lib/libGL.so.1.7.0:   ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, BuildID[sha1]=678653f6a41d06264a4f558d41b61045b5495f61, stripped
/usr/lib64/libGL.so:       symbolic link to `libGL.so.1.2.0'
/usr/lib64/libGL.so.1:     symbolic link to `libGL.so.1.2.0'
/usr/lib64/libGL.so.1.2.0: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=ff6de922c57fb9e18e0e2d429dd7f395c42672c1, stripped

Also I installed "SDL" and "mesa" for gui programming.

Substitution failure with `std::function` and previously deduced template parameter - why?

Consider the following code:

template <typename> 
struct S { };

void g(S<int> t);

template <typename T>
void f(T, std::function<void(S<T>)>);

When attempting to invoke

f(0, g);

I get the following error:

error: no matching function for call to 'f'
    f(0, g);
    ^

note: candidate template ignored: could not match 
      'function<void (S<type-parameter-0-0>)>' 
      against 'void (*)(S<int>)'
void f(T, std::function<void(S<T>)>);
     ^

live example on godbolt.org

While I understand that generally the type of the std::function parameter can't be deduced as it is a non-deduced context, in this case T can first be deduced by the passed argument 0.

I would expect that after deducing T=int, the compiler would substitute T everywhere in the signature and then attempt to construct the std::function parameter with the argument g.

Why is that not the case? I presume that the ordering in which substitution/deduction happens has something to do with this, but I'd like to see the relevant Standard wording.

Bonus question: is this something that could potentially be changed in a future Standard while preserving backwards compatibility, or is there a fundamental reason why this kind of substitution doesn't work?

C++ Lambda returns empty string

I have a class Fee.

    class Fee
{
private:
    std::string _code;
    int _value;
    std::string _description_EN;
    std::string _description_UA;
    std::vector<std::function<std::string()>> get_description;
public:
    //CONSTRUCTORS
    Fee(int value, std::string_view code, std::string_view description_EN, std::string_view description_UA);
    Fee(const std::string _csv_line, const char separator);
    Fee(const Fee &) = delete;
    Fee(Fee &&) = default;
    //OPERATORS
    Fee &operator=(const Fee &) = delete;
    Fee &operator=(Fee &&) = default;
    Fee &operator++() = delete;
    Fee &operator++(int) = delete;
    Fee &operator--() = delete;
    Fee &operator--(int) = delete;
    Fee &operator+(const Fee &other) = delete;
    Fee &operator-(const Fee &other) = delete;
    Fee &operator+=(const Fee &other) = delete;
    Fee &operator-=(const Fee &other) = delete;
    Fee &operator/(const Fee &other) = delete;
    Fee &operator*(const Fee &other) = delete;
    Fee &operator/=(const Fee &other) = delete;
    Fee &operator*=(const Fee &other) = delete;
    Fee &operator%(const Fee &other) = delete;
    Fee &operator%=(const Fee &other) = delete;
    //SETTERS
    void set_new_value(int value);
    //GETTERS
    std::string code();
    int value();
    std::string description(Language language = Language::EN);
    //FUNCTIONS

    //DESTRUCTOR
    ~Fee() = default;
};

And class FeeList which stores map of Fees

class FeeList
{
private:
    std::map<std::string, Fee> _fee_list;
    FeeList() = default;
public:
    static FeeList &fee_list();
    //CONSTRUCTORS
    FeeList(const FeeList &) = delete;
    FeeList(FeeList &&) = delete;
    //OPERATORS
    FeeList &operator=(const FeeList &) = delete;
    FeeList &operator=(FeeList &&) = delete;
    //SETTERS

    //GETTERS
    Fee &fee(const std::string &code);
    //FUNCTIONS
    void addFee(Fee &fee);
    void from_csv_file(const std::string &inv_file, const std::string &um_file, const std::string &id_file, const std::string &tr_file, const char separator);
    //DESTRUCTOR
    ~FeeList() = default;

};

Constructor of class Fee has the following lines of code which fill up the "get_description" vector by lambdas

get_description.resize(2);
    get_description[static_cast<size_t>(fee::Language::EN)] = [this]()->std::string{return _description_EN;};
    get_description[static_cast<size_t>(fee::Language::UA)] = [this]()->std::string{return _description_UA;};

Those lambdas are invoked by function "description(fee::Language::)" which should return description in appropriate language. Implementation is quite strait forward

std::string fee::Fee::description(Language language)
{
    return get_description[static_cast<size_t>(language)]();
}

The problem is that the empty string is returned from lambda. I have created simple class to test such approach and it worked as expected. I can't figure out were is the problem. I'm getting values of other variables (code and value) so object is stored correctly.

Passing a double pointer as argument to a function which expects a reference to a std::vector

Is there any possible way to pass a double pointer as argument to a function which expects a reference to a std::vecto argument in C ++11

jeudi 26 septembre 2019

I'm learning Mac development,could you please suggest me some good ways to learn it better?Thanks

I have learnt C/C++、Java、python,I will learn this for job.

member function not found after static cast from base to derived

I am trying to build a function called 'step', which takes a base class pointer and does some things. Currently, I am using a dummy base class in order to enable a common interface.

#include <iostream>

using namespace std;

class gym_action //dummy base
{
public:
    virtual ~gym_action(){}
};

template<typename T>
class action_helper : public gym_action
{
    public :
        action_helper(T a) : action_item(a){}
        T get_action() {return action_item;}

    private:
       T action_item;

};

void step(gym_action* act)
{
    act = dynamic_cast<action_helper<int>*>(act);
    cout<<act->get_action()<<endl;
}

int main()
{

    action_helper<int> a(2);
//I will have more action_helper instansiations, like action_helper<Eigen::VectorXf> etc
    cout<<a.get_action()<<endl;
    step(&a);

}

This code fails with gym_class has no member function get_action. Clearly, the reason for this is that there is no virtual function get_action in the base class.

However, how can I define this? The reasons I can't currently is that each templatized get_action function returns a different type T. One possible way is I define every possible overload ahead of time in the base class, but this seems like a bad design Thoughts?

Correct way to initialize and assign a shared Pointer

This is the way i am initializing a shared pointer.

std::shared_ptr<ClassA> ClassA::Clone() const
{
    ClassA* smt = new ClassA(*this);
    return std::shared_ptr<ClassA>(smt);
}

Is this the correct way to assign a shared pointer.

Trying to use

I got this error while working in Dev-C++:

#ifndef _CXX0X_WARNING_H
#define _CXX0X_WARNING_H 1

#if __cplusplus < 201103L
#error This file requires compiler and library support for the \
ISO C++ 2011 standard. This support is currently experimental, and must be \
enabled with the -std=c++11 or -std=gnu++11 compiler options.
#endif
#endif

I was trying to use the rand() function in random library. How do I fix this issue? Please be specific - I am new to programming and don't understand a lot yet. I've seen a similar question asked a couple other places but people just say "do what the error says" which is not helpful when I don't understand it or how to fix it. Do I need a different compiler? How do I do that?

How to conditionally add element to std::array - C++11

I have a simple program:

#include <array>
#include <iostream>
#include <functional>
#include <algorithm>

using namespace std;

int main(){
    array<int, 5> myArr = {3, 10, 0, 5, 7};
    int badNum = 0;
    for(int item : myArr){
        cout << item << endl;
    }

    cout << "\n" << endl;
    cout << "\n" << endl;

    sort(myArr.begin(), myArr.end(), greater<int>());

    for(int item : myArr){
        cout << item << endl;
    }

    array<int, 3> goodThree;

    for (unsigned int i = 0; i < myArr.size(); i++){
        if(myArr[i] != badNum){
            // goodThree.append(myArr[i]); <-- This is where I am stuck
        }
    }

}

I am stuck on trying to add an element to a std::array. I know in std::vector I can use push_back method, but on a std:array, how to add elements to it? I am coming from Python 3.x where we have the append method for a list.

I have looked at the C++ std::array documentation but there is no method for adding a single element.

I have also looked at:

http://www.cplusplus.com/forum/beginner/67707/

http://www.cplusplus.com/forum/beginner/86394/

http://www.cplusplus.com/forum/beginner/152125/

But these are all for vectors or the primitive int[5] myArr types, not std::array.

boost::weak_ptr to a default constructed Object : lock() method returns a NULL pointer when a similar empty shared_ptr is expected

I have a bit of code where the original object is default constructed:

SimulatedIndexFixingStore::SimulatedIndexFixingStore() : Singleton<SimulatedIndexFixingStore>(),
        simulatedFixings_(Dictionary())
        {}

Dictionary is a typedef to a complicated unordered_map of map of map.

My decision is to use weak_pointers instead of shared ones to manage the proper deletion of static singleton instances at the end of my program. In the below bit:

 boost::weak_ptr<SimulatedIndexFixingStore>& simulatedIndicesFixings_; <--- default constructed using SimulatedIndexFixingStore()

auto p = simulatedIndicesFixings_.lock(); <--- here the shared ptr p has a NULL pointer!

My understanding from reading lock() definition on cppreference is when an object is default constructed, I would get a shared_ptr p that points to an empty object, but not a NULL pointer!

Whereas, looking inside the boost implementation of weak_ptr, it makes perfect sense:

template<class Y>
    shared_ptr( weak_ptr<Y> const & r, boost::detail::sp_nothrow_tag )
    BOOST_NOEXCEPT : px( 0 ), pn( r.pn, boost::detail::sp_nothrow_tag() )
    {
        if( !pn.empty() ) // px is left null if the object pn points is empty/default
        {
            px = r.px;
        }
    }

Is my understanding correct? Is there a difference in implementation between the two libraries? If so, can you please let me know of any other way to re-use my weak_ptr to the default constructed object in later code, other than having to use the std::weak_ptr implementation.

Thanks

Amine

Could anyone please help me how to go one level up from the GetCurrentDirectory() path in C++

Using GetCurrentDiretcory() function, I am getting the current directory path like as shown below:

C:\PCPE\src\PCPEJob

My requirement is, from the GetCurrentDirectory() path I need to go one level up i.e., C:\PCPE\src

So that I can append new directory to this path.

Could anyone please help me how to go one level up from the GetCurrentDirectory() path?

How to make buffer size dynamically in C++?

I receive string_value with random size every time less than 10000 size and I want to make data buffer size dynamically in C++. Currently using array.

char buffer[10000];
memset(buffer,0,10000);

and using strncpy() function.

strncpy(buffer, string_value, 10000);

Where are the labels of the Q3DScatter grapph?

I was expecting to see the labels by doing the following:

#include "mainwindow.h"

#include <Q3DScatter>

using namespace QtDataVisualization;

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) 
{
    Q3DScatter *graph = new Q3DScatter;
    QWidget *widget = QWidget::createWindowContainer(graph);
    setCentralWidget(widget);
    graph->axisX()->setLabels(QStringList{"a", "b", "c"});
}

MainWindow::~MainWindow() {}

But nothing, and I found no method to show/hide labels, so where are the labels?

enter image description here

how to use c++ void_t correctly?

I am trying to practice on void_t usage but following code gives this compilation error.

is_fun is typedef in CompS struct so I think Comps::is_fun should be valid.

Is there anything I missed here?

template <typename T, typename Comp, typename = void_t<>>
class my_set
{
    public:
        my_set() : mem(5){}
        T mem;
};

template <typename T, typename Comp, void_t<typename Comp::is_fun> >
class my_set 
{
    public:
        my_set() : mem(10){}
        T mem;
};

struct CompS
{
    typedef int is_fun;
};

int main()
{
    my_set<int, CompS> a;
    std::cout << a.mem << std::endl;



    return 0;
}

voidt.cpp:17:38: error: ‘void’ is not a valid type for a template non-type parameter
 template <typename T, typename Comp, void_t<typename Comp::is_transparent> >
                                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
voidt.cpp:9:38: error: template parameter ‘class<template-parameter-1-3>’
 template <typename T, typename Comp, typename = void>
                                  ^~~~~~~~
voidt.cpp:18:7: error: redeclared here as ‘<typeprefixerror><anonymous>’
 class my_set

"Make run" print "bin/prog" in terminal

When i run "make run" in terminal, the program print bin/prog, but i don't want this, look the Makefile

CC := g++
CFLAGS := -W -Wall -ansi -std=c++17 -lstdc++fs -pedantic
SRCFILES := $(wildcard src/*.cpp)
run: bin/prog
    bin/prog

How to Create a list of numbers in C++ such that it can choose a random number?

Hello I have a code snippet here in C++ which spawns a red box in Gazebo at the position 'y' which is here, the spawn_model_req.initial_pose.position.y variable. I want to create a list of numbers e.g. [-0.2,-0.3,-0.4,0.4,0.5] and choose random number for that variable to randomly spawn the red box at any 'y' position.

int i = 0;

  while (ros::ok()){
      std::string index = intToString(i);
      std::string model_name;

      spawn_model_req.initial_pose.position.y = (float)rand()/(float)(RAND_MAX) * 0.4;  // random between -0.4 to 0.4
      ROS_INFO_STREAM("y position of new box: "
      << spawn_model_req.initial_pose.position.y);

      model_name = "red_blocks_" + index;  // initialize model_name
      spawn_model_req.model_name = model_name;
      spawn_model_req.robot_namespace = model_name;
      spawn_model_req.model_xml = red_xmlStr;

P.S: I have attached the full code below

// spawn the red blocks on the conveyor belt
// and give them initial speed (by apply_body_wrench) to slide on conveyor

//ros communications:
  // spawn model throught gazebo service: /gazebo/spawn_urdf_model
  // initialize blocks speed: /gazebo/apply_body_wrench
  // get urdf file path of blocks from parameter servicer
  //publish all current blocks through topic: /current_blocks

  #include <ros/ros.h>
  #include <iostream>
  #include <sstream>
  #include <fstream>
  #include <string>
  #include <urdf/model.h>
  #include <gazebo_msgs/SpawnModel.h>
  #include <gazebo_msgs/ApplyBodyWrench.h>
  #include <std_msgs/Int8MultiArray.h>
  #include <gazebo_msgs/SetModelState.h>

  //int to string converter
  std::string intToString (int a) {
     std::stringstream ss;
     ss << a;
     return ss.str();
  }

  int main(int argc, char **argv) {
      ros::init(argc, argv, "blocks_spawner");
      ros::NodeHandle nh;
      srand(time(0));
      //service client for service /gazebo/spawn_urdf_model
      ros::ServiceClient spawnClient = nh.serviceClient<gazebo_msgs::SpawnModel>("/gazebo/spawn_urdf_model");
      gazebo_msgs::SpawnModel::Request spawn_model_req;
      gazebo_msgs::SpawnModel::Response spawn_model_resp;

      ros::ServiceClient wrenchClient = nh.serviceClient<gazebo_msgs::ApplyBodyWrench>("/gazebo/apply_body_wrench");
      gazebo_msgs::ApplyBodyWrench::Request apply_wrench_req;
      gazebo_msgs::ApplyBodyWrench::Response apply_wrench_resp;

      ros::ServiceClient setstateClient = nh.serviceClient<gazebo_msgs::SetModelState>("/gazebo/set_model_state");
      gazebo_msgs::ApplyBodyWrench::Request set_state_req;
      gazebo_msgs::ApplyBodyWrench::Response set_state_resp;

      //publisher for current_blocks
      ros::Publisher current_blocks_publisher = nh.advertise<std_msgs::Int8MultiArray>("current_blocks",1);
      std_msgs::Int8MultiArray current_blocks_msg;
      current_blocks_msg.data.clear();

      // make sure /gazebo/spawn_urdf_model service is service_ready
      bool service_ready = false;
      while (!service_ready){
        service_ready = ros::service::exists("/gazebo/spawn_urdf_model", true);
        ROS_INFO("waiting for spawn_urdf_model service");
        ros::Duration(0.5).sleep();
      }
      ROS_INFO("spawn_urdf_model service is ready");

      service_ready = false;
      while (!service_ready) {
          service_ready = ros::service::exists("/gazebo/apply_body_wrench", true);
          ROS_INFO("waiting for apply_body_wrench service");
          ros::Duration(0.5).sleep();
      }
      ROS_INFO("apply_body_wrench service is ready");

      service_ready = false;
      while (!service_ready) {
          service_ready = ros::service::exists("/gazebo/set_model_state", true);
          ROS_INFO("waiting for set_model_state service");
          ros::Duration(0.5).sleep();
      }
      ROS_INFO("set_model_state service is ready");

      //get file path of blocks from parameter service
      std::string red_box_path;
      bool get_red_path;
      get_red_path = nh.getParam("/red_box_path", red_box_path);

      if (!(get_red_path)){
          return 0;}
          else{ROS_INFO_STREAM(red_box_path << " has been extracted");
}

      std::ifstream red_inXml(red_box_path.c_str());
      std::stringstream red_strStream;
      std::string red_xmlStr;

      /*red_inXml.open(red_box_path.c_str());*/
      red_strStream << red_inXml.rdbuf();
      red_xmlStr = red_strStream.str();
     // ROS_INFO_STREAM("urdf: \n" <<red_xmlStr);
      // prepare the pawn model service message
      spawn_model_req.initial_pose.position.x = 2;
      spawn_model_req.initial_pose.position.z = 0.2;
      spawn_model_req.initial_pose.orientation.x=0.0;
      spawn_model_req.initial_pose.orientation.y=0.0;
      spawn_model_req.initial_pose.orientation.z=0.0;
      spawn_model_req.initial_pose.orientation.w=1.0;
      spawn_model_req.reference_frame = "world";

      ros::Time time_temp(0, 0);
      ros::Duration duration_temp(0, 1000000);
      apply_wrench_req.wrench.force.x = -5.1;
      apply_wrench_req.wrench.force.y = 0.0;
      apply_wrench_req.wrench.force.z = 0.0;
      apply_wrench_req.start_time = time_temp;
      apply_wrench_req.duration = duration_temp;
      apply_wrench_req.reference_frame = "world";

      int i = 0;

      while (ros::ok()){
          std::string index = intToString(i);
          std::string model_name;

          spawn_model_req.initial_pose.position.y = (float)rand()/(float)(RAND_MAX) * 0.4;  // random between -0.4 to 0.4
          ROS_INFO_STREAM("y position of new box: "
          << spawn_model_req.initial_pose.position.y);

          model_name = "red_blocks_" + index;  // initialize model_name
          spawn_model_req.model_name = model_name;
          spawn_model_req.robot_namespace = model_name;
          spawn_model_req.model_xml = red_xmlStr;

          bool call_service = spawnClient.call(spawn_model_req, spawn_model_resp);
          if (call_service) {
              if (spawn_model_resp.success) {
                  ROS_INFO_STREAM(model_name << " has been spawned");
              }
              else {
                  ROS_INFO_STREAM(model_name << " spawn failed");
              }
          }
          else {
              ROS_INFO("fail in first call");
              ROS_ERROR("fail to connect with gazebo server");
              return 0;
          }

          // prepare apply body wrench service message
          apply_wrench_req.body_name = model_name + "::base_link";

          // call apply body wrench service
          call_service = wrenchClient.call(apply_wrench_req, apply_wrench_resp);
          if (call_service) {
              if (apply_wrench_resp.success) {
                  ROS_INFO_STREAM(model_name << " speed initialized");
              }
              else {
                  ROS_INFO_STREAM(model_name << " fail to initialize speed");
              }
          }
          else {
              ROS_ERROR("fail to connect with gazebo server");
              return 0;
          }

          // publish current cylinder blocks status, all cylinder blocks will be published
          // no matter if it's successfully spawned, or successfully initialized in speed
          current_blocks_publisher.publish(current_blocks_msg);

          // loop end, increase index by 1, add blank line
          i = i + 1;
          ROS_INFO_STREAM("");

          ros::spinOnce();
          ros::Duration(20.0).sleep();  // frequency control, spawn one cylinder in each loop
          // delay time decides density of the cylinders


      }
      return 0;
  }

Access Member Variables using templates

I need a template function that can serve generic purpose of accessing a member variable and operating functions present in that member variable. I have a set of functions to be called and this will solve my purpose.

I have tried the following

class Utilities {
public:
template<typename Container, typename MemberVar, typename Operator>
static void for_all(Container& C, MemberVar memvar, Operator Op) {
    for (auto& element : C) {
        (element.memvar->Op)();
    }
 }
};

I have the following test code where there is class Test that has PrivateImpl and DataStructure holding that privatimpl. Below is the print function that calls the Utilities::for_all function with privateimpl's print function

void Test::print() {
    ::Utilities::for_all(m_vec_struct_privateimpl,&Test::Struct_PrivateImpl::m_privateimpl,&Test::CPrivateImpl::print);
}

Below is the details about all the classes

// Main Class
class Test {
public:
    Test();
    ~Test();
    void print();
private:
    class CPrivateImpl;
    struct Struct_PrivateImpl;
    std::vector<Struct_PrivateImpl> m_vec_struct_privateimpl;
}; //class Utilities

// Class PrivateImpl
class Test::CPrivateImpl {
public:
    CPrivateImpl(std::initializer_list<int>& lst) {
        for (auto& i : lst) {
            m_vec_int.push_back(i);
        }

    }
    void print(int i) {
        cout << i << " ";
    }
private:
    std::vector<int> m_vec_int;

}; //class Test::CPrivateImpl

// Data Structure having PrivateImpl
struct Test::Struct_PrivateImpl {
public:

    Struct_PrivateImpl(int i) {
        m_privateimpl = std::make_shared<Test::CPrivateImpl>(std::initializer_list<int>{100+i,200+i,300+i});

    };
    ~Struct_PrivateImpl() {
    }

//private:
    std::shared_ptr<CPrivateImpl> m_privateimpl;
}; // class WiperSkeletonSomeIP::Struct_PrivateImpl

Test::Test(){
    for(auto i = 0u; i != 3; ++i) {
        Struct_PrivateImpl a_struct_pvtimpl(i);
        m_vec_struct_privateimpl.push_back(a_struct_pvtimpl);
    }
}
void Test::print() {
        ::Utilities::for_all(m_vec_struct_privateimpl,&Test::Struct_PrivateImpl::m_privateimpl,&Test::CPrivateImpl::print);
    }    

// This is the main function
int main() {
    Test t;
    t.print();
}

I am getting error message saying memvar has function Op.

This is an example code I have a lot of functions to be called within PrivateImpl class.

Please help me how to solve this.

mercredi 25 septembre 2019

Why copy constructor is called instead of move constructor in my code?

I'm trying to understand a move constructor and rvalue reference. So I tried this code on https://www.onlinegdb.com/online_c++_compiler. But the result confuses me.

#include <iostream>
#include <type_traits>


class A {
public:
  A() { std::cout << "Constructed" << std::endl; }
  A(const A& )= delete;
  A(A&&) { std::cout << "Move Constructed" << std::endl; }
};

int
main ()
{
  A&& a = A();
  A b = a; // error: use of deleted function ‘A::A(const A&)’
  //A b = static_cast<decltype(a)>(a); // This works, WTF?
  std::cout << std::is_rvalue_reference<decltype(a)>::value << std::endl; // pretty sure a is rvalue reference.

  return 0;
}

c++: getline argument list type infered as std::ifstream instead of std::ifstream&?

class TextQuery
{
public:
    using line_no = std::vector<std::string>::size_type;
    TextQuery(std::ifstream&);
    QueryResult query(const std::string&) const;
private:
    std::shared_ptr<std::vector<std::string>> file;
    std::map<std::string, std::shared_ptr<std::set<line_no>>> vm;
};

TextQuery::TextQuery(std::ifstream &is): file(new std::vector<std::string>)
{
    std::string text;
    while (std::getline(is, text)) {
        file->push_back(text);
        int n = file->size() - 1;
        std::istringstream line(text);
        std::string word;
        while (line >> word) {
            auto& lines = vm[word];
            if (!lines) {
                lines.reset(new std::set<line_no>);
            }
            lines->insert(n);
        }
    }
}

IDE: visual studio 2019 error line:

while (std::getline(is, text)) {

the IDE inferred the argument list types of the getline function is "std::ifstream, std::string". so this is inconsistent with the signature of the getline (string) function. but is parameter is from function parameter which has type of "std::ifstream &". I am confused here why IDE infer it as "std::ifstream" instead of "std::ifstream &" ? can anybody give some thoughts about how to fix this?

std::vector

I have an array std::vector<int> and an enum class Foo : int. Is there a better way to cast or convert than a reinterpret_cast?

std::vector<int> v;
auto& c = *reinterpret_cast<std::vector<Foo>*>(&v);

How does C++ knows child class calls a parent method?

I don't know how to summarize my question so couldn't find an answer on Google.

When overriding a parent method,

void Child::method(){
    //stuff
    Parent::method();
}

Works perfectly. But the parent method requires the information from the Child class instance to work properly, which is not given as arguments. So my question is, does C++ have a mechanism to let the Parent know which instance of a Child class calls a Parent method, like without doing Parent::method(this) ?

The thing that makes me think this is, if you do something like this,

int main(){
    SomeParentClass::someMethod();
}

It gives: error: call to non-static member function without an object argument. So the compiler needs to know the instance, which was not also given in the child class. But did not raise an error so it must have known the instance.

Edit: I added the Qt tag because I am experimenting on a Qt class. So that I can give an example if needed.

Polymorphism with Distribution in C++11

I have a problem where I want a single object to represent any distribution class (polymorphism) used in random library in c++11. Since distribution does not have a common base class as far as I know I am using factory pattern to solve my problem. Is there a better way to do so ? I am adding the code below which has some errors

#include <iostream>
#include<random>

using namespace std;

class Distribution 
{
public:
    void *distribution;
    virtual void get_distribution() = 0;
};

class normal_dist: public Distribution
{
public:
    //normal_distribution<double> *distribution;
    void get_distribution()
    {
        distribution = new normal_distribution<double>(5.0,2.0); 
    }
};

class uniform_real_dist: public Distribution
{
public:
    //uniform_real_distribution<double> *distribution;
    void get_distribution()
    {
        distribution = new uniform_real_distribution<double>(0.0,1.0);
    }
};

class Helper
{
public:
    Distribution *dist;
    default_random_engine generator;

Helper(string dist_type) 
{
    if(dist_type == "normal")
    {
        dist = new normal_dist;
        dist->get_distribution();
    }
}
};


int main() {

Helper *help = new Helper("normal");
cout<<(*(help->dist->distribution))(help->generator);


// your code goes here
return 0;
}

My questions are three fold 1) Is there a base class of distribution 2) if no, is there a way to create polymorphism 3) Whether the above code is correct approach and what is the bug and how to solve this. I would be very thankful if someone could help me on this

Configure VSCode for C++ with WSL

I am new to C++. I have configured VSCode with WSL. Added g++ compiler. I have a Folder with many Cpp files. I need to compile and execute them. I have modified Tasks.json to build Application.cpp file. But i see only .o files and not .exe files. What am i missing?

Can't Call Function Within Switch Case - C++

I am trying to run encryption program of some sort but i can't call void enc, Source Code:

#include <iostream>
#include <conio.h>
#include <windows.h>
#include <algorithm>
#include <string>

using namespace std;

int x,y,z,a,b,c,n;
char tabs[26][26],temp[512];
string input,output,Key;

void open();
void tableau();
void inchar();
void enc();
void dec();

int main() {
  open();
  cout << "1.\tEncrypt \n2.\tDecrypt \nOption: "; cin >> a;
  switch (a) {
    case 1:
      enc(); cout << a << "Debugger";
      break;
    case 2:
      dec();
    break;
  }
  return 0;
}

void enc(){
  void open();
  void inchar();
}

void dec(){

}

void inchar(){
  cout << "input: "; cin >> input; z = input.size();
  char dispos[input.size() + 1];
  copy(input.begin(),input.end(),dispos); dispos[input.size()] = '\0';
  for (int i = 0; i < z; i++) {
    temp[i] = dispos [i];
  }
}

void tableau() {
  cout << "Initialize Table Construct!!" << endl;
  for (int i = 0; i < 26; i++) {
    for (int j = 0; j < 26; j++) {
      x = (i + j) % 26; y = x + 65;
      tabs[i][j] = y;
      cout << tabs[i][j] << " ";
    }
    cout << endl;
  }
}

void open() {
  cout << "Well Hello There";
}

every time i choose option 1 the debugger cout kept on appearing. if the debugger is erased then the code just end.

P.S: I've done moving the function call to before the switch but still it does nothing. P.S.S: Sorry for bad English.

Why typename is not needed in this case?

I was reading about the usage of typename in C++ template programming (e.g. this Q/A). To me, it seems that when using a dependent nested type name, we should use typename for avoiding parsing ambiguity. I also checked this on Scot Meyers book effective C++, item #42.

But what is strange for me is that the same example in the book, works without the typename. Here is the code:

template<class C>
void Print2nd(const C & cont)
{
   if (cont.size() >= 2)
   {
      C::const_iterator * iter1 = new C::const_iterator(cont.begin());  // why typename is NOT needed?
      C::const_iterator   iter2 = cont.begin();                         // why typename is NOT needed?
      (*iter1)++;
      iter2++;
      int value1 = **iter1;
      int value2 = *iter2;

      std::cout << "The value of 2nd with pointer is: " << value1 << std::endl;
      std::cout << "The value of 2nd without pointer is: " << value2 << std::endl;
   }
}


int main()
{
   std::vector<int> vect = {1,2,3,4,5,6};
   Print2nd(vect);
   return 0;
}

I am using VS2015. So, the Q is that why typename is not needed in this context? Is there any upgrade in recent C++ compilers to avoid using typename in such a context? Or I am doing a mistake in the code?

How to call an implementation of an interface in c++ from another class?

I have an abstract class, let's say A, which contains a pure virtual function with an access specifier as protected. Another class, let's say B, overrides the interface and implement function List().

class A {
 public:
  ...
 protected:
  virtual std::vector<std::string> List() = 0;
}
class B: public A {
 protected:
  std::vector<std::string> List() override {
   //Implementation for the method
  }
}

My question is that now I have another class, C, which needs to call implemented interface List() from class B so that I can store the returned result in class C. How can I call an interface in class C?

PS: I can change the access specifier of the method to public in class B if that can solve the problem.

Extracting a substring to the last-nth delimiter C++

I am trying in C++ to find

  1. the most performant
  2. the most elegant

code that takes a string and an integer and for a given delimiter, let's say ".", results to the nth from the last substring.

Example Input:

string "a.b.c.d.e" and delimFromEndLevel = 1 => string "a.b.c.d"

string "a.b.c.d.e" and delimFromEndLevel = 2 => string "a.b.c"

etc.

Starting point is the following code:

void elaborateParent( const std::string& input, unsigned int levels )
{
    std::size_t cutOffIndex = std::string::npos;
    while (levels > 0)
    {
        cutOffIndex = input.rfind('.', cutOffIndex);
        if (cutOffIndex == std::string::npos)
            std::cout << "Not enough levels to go up!" << std::endl; 
        levels--;
        if (levels>0)
        {
            if (cutOffIndex>0)
                cutOffIndex--;
            else
                std::cout << "Not enough levels to go up!" << std::endl;
        }
    }
    std::string result = input.substr(0, cutOffIndex);
    std::cout << "Elaboration parent result: '" << result << "'" << std::endl;
}

mardi 24 septembre 2019

Ofstream creates just empty file but not writing

I want my arrays to be printed as "testOutput.txt" but when I run the code, it just creates empty file and does not write.

Also, my code makes Segmentation Fault, which I strongly suspect causing the problem now. But I have no idea why it happens, and why there were no error when I tested with std::cout.

I tested those data with std::cout instead of ofstream fout, and it worked well as I expected.

    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <string>

    /*
        Functions are defined here
    */

    int main(int argc, char *argv[])
    {
        int i, j, k, len1, len2, len3, max1, max2, min1, min2, index, input4, input5, input6, c, theDeleted, pos0;
        int* arr1;
        int* arr2;
        int* arr3;
        int* duplicate;

        std::string line;
        std::string test;
        std::string errorMessage = "Error: It is not a numeric input.\n";
        std::stringstream ss;

        std::ifstream fin("testInput.txt");

        std::getline(fin, line);
        ss.str(line);
        ss >> test;
        if (isNumeric(test))
        {
            len1 = std::stoi(test);
            arr1 = new int[len1];
        }
        else
        {
            std::cout << errorMessage;
            return 0;
        }
        ss >> test;
        if (isNumeric(test))
        {
            len2 = std::stoi(test);
            arr2 = new int[len2];
        }
        else
        {
            std::cout << errorMessage;
            return 0;
        }

        std::getline(fin, line);
        ss.clear();
        ss.str(line);
        for (i = 0; i < len1; i++)
        {
            ss >> test;
            if (isNumeric(test))
            {
                arr1[i] = std::stoi(test);
            }
            else
            {
                std::cout << errorMessage;
                return 0;
            }
        }

        std::getline(fin, line);
        ss.clear();
        ss.str(line);
        for (i = 0; i < len2; i++)
        {
            ss >> test;
            if (isNumeric(test))
            {
                arr2[i] = std::stoi(test);
            }
            else
            {
                std::cout << errorMessage;
                return 0;
            }
        }

        ss.clear();
        fin >> input4 >> input5 >> input6;

        if (fin.is_open())
            fin.close();

        std::ofstream fout("testOutput.txt");

        max1 = maxElement(arr1, len1);
        max2 = maxElement(arr2, len2);
        min1 = minElement(arr1, len1);
        min2 = minElement(arr2, len2);
        fout << "1)\narr1: " << max1 << "\narr2: " << max2 << "\n";
        fout << "2)\narr1: " << min1 << "\narr2: " << min2 << "\n";
        fout << "3)\narr1: " << min1 << " " << max1 << "\narr2: " << min2 << " " << max2 << "\n";

        fout << "4)\n";                                                                             //4
        sortAscBub(arr1, len1);
        sortAscBub(arr2, len2);
        fout << "arr1: ";
        for (i = 0; i < len1; i++)
            fout << arr1[i] << " ";
        fout << "\narr2: ";
        for (i = 0; i < len2; i++)
            fout << arr2[i] << " ";
        fout << "\n";

        fout << "5)\n";                                                                             //5
        sortDscSel(arr1, len1);
        sortDscSel(arr2, len2);
        fout << "arr1: ";
        for (i = 0; i < len1; i++)
            fout << arr1[i] << " ";
        fout << "\narr2: ";
        for (i = 0; i < len2; i++)
            fout << arr2[i] << " ";
        fout << "\n";

        fout << "6)\narr3: ";                                                                           //6
    //  merge(arr1, arr2, arr3, len1, len2, len3);
        i = len1 - 1, j = len2 - 1, k = 0;
        len3 = len1 + len2;
        arr3 = new int[len3];
        while (k < len3)
        {
            if (i < 0)
                arr3[k++] = arr2[j--];
            else if (j < 0)
                arr3[k++] = arr1[i--];
            else if (arr1[i] < arr2[j])
                arr3[k++] = arr1[i--];
            else
                arr3[k++] = arr2[j--];
        }
        for (i = 0; i < len3; i++)
            fout << arr3[i] << " ";
        fout << "\n";
        delete[] arr1;
        delete[] arr2;

        index = searchElement(input4, arr3, len3);
        fout << "7)\nIndex: " << index << "\n";                                                     //7

    //  removeDupe(arr3, len3, duplicate, c);
        j = 0, c = 0;
        int check = -1;
        int* temp1;
        int* temp2;
        temp1 = new int[len3];
        temp2 = new int[len3];
        for (i = 0; i < len3; i++)
        {
            if (check == arr3[i])
            {
                if (c=0)
                {
                    temp2[c++] = check;
                }
                else if (check != temp2[c - 1])
                {
                    temp2[c++] = check;
                }
            }
            else
            {
                temp1[j++] = arr3[i];
                check = arr3[i];
            }
        }
        len3 = len3 - c;
        for (i=0; i< len3; i++)
            arr3[i] = temp1[i];
        for (i=0; i<c; i++)
            duplicate[i] = temp2[i];
        delete[] temp1;
        delete[] temp2;
        fout << "8)\nDuplicate Elements: ";                                                         //8
        for (i = 0; i < c; i++)
            fout << duplicate[i] << " ";
        fout << "\narr3: ";
        for (i = 0; i < len3; i++)
            fout << arr3[i] << " ";
        fout << "\n";

        theDeleted = delIndex(input5, arr3, len3);
        fout << "9)\nElement: " << theDeleted << "\narr3: ";                                            //9
        for (i = 0; i < len3; i++)
            fout << arr3[i] << " ";
        fout << "\n";

        pos0 = searchRecur(input6, arr3, 0, len3);
        insert0(pos0, arr3, len3);
        fout << "10)\narr3: ";                                                                          //10
        for (i = 0; i < len3; i++)
            fout << arr3[i] << " ";
        fout << "\n\n";

        delete[] arr3;
    //  delete[] duplicate;

        fout.flush();

        if (fout.is_open())
            fout.close();

        return 0;
    }

I expect the output file with few numbers in it, but the file is empty.

how to parse txt file using c++

this is the txt file to read. its on specific format

by using sstream and getline function i have to extract id, title, author ,abstract and store all the respective words in vector. i am stuck.

using namespace std;

int main(){

string filename;
cout<<"Please enter the name of the collection file: ";
getline(cin,filename);

fstream file(filename.c_str());

if(!file)
{
    cout<<"Error!! opeaning the file. Please check your file name. \n";
    return EXIT_FAILURE;
}

else{

How would I output this in C++ in my main function, and what functions do I need?

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Note: Do not modify the linked list.

Example 1:
Input: head = [3,2,0,-4], pos = 1

Output: tail connects to node index 1

Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:
Input: head = [1,2], pos = 0

Output: tail connects to node index 0

Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:
Input: head = [1], pos = -1

Output: no cycle

Explanation: There is no cycle in the linked list.

#ifndef LISTNODE_H_
#define LISTNODE_H_
#include <iostream>

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(head == NULL)
            return NULL;
        ListNode *p1 = head, *p2 = head;
        do{
            p1 = p1->next;
            p2 = p2->next;
            if(p2 != NULL)
                p2 = p2->next;
            else
                break;

        }while(p1 != p2 && p2 != NULL);
        if(p2 == NULL)
            return NULL;
        p1 = head;
        while(p1 != p2){
            p1 = p1->next;
            p2 = p2->next;
        }
        return p1;
    }
};

#endif

How to iterate list of object pointed by pointer

how to get data from list of objects which is pointed by a pointer.

std::list<object> *myList;

std::list<object>::iterator itr;

for(itr = myList.begin(); itr != myList.end(); itr++) {
  std::cout << itr->data;
}

Moving object of lists in C++ to another object

I'm trying to understand how this piece of code is working.

// Example program
#include <iostream>
#include <string>
#include <list>

struct complex
{
  int n;
  std::string str;
  complex(int n): n(n), str("String form " + std::to_string(n)) {}
};

struct Node
{
    Node(){std::cout<<"creating obj\n";}
    Node(const Node &a){ll = a.ll; pll = a.pll;}
    Node(Node &&a){ll = std::move(a.ll); pll = std::move(a.pll);}
    Node& operator=(const Node &a){ll = a.ll; pll = a.pll; return *this;}
    Node& operator=(Node &&a){ll = std::move(a.ll); pll = std::move(a.pll); return *this;}

    ~Node()
    {
      std::cout<<"Destroying object\n";
      for(auto iter : ll)
      {
        iter = 0;
      }
      for(auto iter : pll)
      {
        delete(iter);
        iter = nullptr;
      }
    }

    std::list<int> ll;
    std::list<complex*> pll;
};

Node CreateNode()
{
    Node n;
    n.ll.push_back(1);
    n.ll.push_back(2);
    n.ll.push_back(3);
    n.ll.push_back(4);
    n.ll.push_back(5);
    n.ll.push_back(6);
    n.ll.push_back(7);

    n.pll.push_back(new complex(11));
    n.pll.push_back(new complex(21));
    n.pll.push_back(new complex(31));
    n.pll.push_back(new complex(41));
    n.pll.push_back(new complex(51));
    n.pll.push_back(new complex(61));
    n.pll.push_back(new complex(71));

    return std::move(n);
}

int main()
{
  Node m;

  std::cout<<"Before assigning Nodes\n";
  for(auto iter : m.ll)
  {
      std::cout<<iter<<" ";
  }
  std::cout<<"\n";
  for(auto iter : m.pll)
  {
      std::cout<<iter->n<<", "<<iter->str<<" --> ";
  }
  std::cout<<"\n";

  m = CreateNode();

  std::cout<<"After assigning Nodes\n";
  for(auto iter : m.ll)
  {
      std::cout<<iter<<" ";
  }
  std::cout<<"\n";
  for(auto iter : m.pll)
  {
      std::cout<<iter->n<<", "<<iter->str<<" --> ";
  }
  std::cout<<"\n";
  return 0;
}

In the copy constructor or in the copy assignment operator, I'm just passing the list, which has a discrete memory allocation. How is it possible that passing only the a.pll in my move semantics moves the whole lot of the memory to the next object? I expected I need to go though each of the list objects and then move them across.

But No. It is simply working like magic, just by moving a.pll to other object. How is going on internally?

You can see this in action here: https://repl.it/repls/WildComfortableLesson

Is it better to pass by value for moveable types instead of overloading functions?

I want to reduce copying to a minimum, especially for expensive types/classes. So I could define overloads like this:

void SetParams(const std::map<int, std::string> &params) { mParams = parameters; }
void SetParams(std::map<int, std::string> &&params) { mParams = std::move(params); }
void SetBoardInfo(const DataInfoStruct &board_info) { mBoardInfo = board_info; }
void SetBoardInfo(DataInfoStruct &&board_info) { mBoardInfo = std::move(board_info); }

in a class that has a std::map member variable called mParams and a DataInfoStruct struct member called mBoardInfo.

Since DataInfoStruct has no user defined constructors or destructors I assume that it has an implicit move constructor.

Then I can invoke either one of the overloads with an lvalue or rvalue. However, I could just have one version of each function like so:

void SetParams(std::map<int, std::string> params) { mParams = std::move(params); }
void SetBoardInfo(DataInfoStruct board_info) { mBoardInfo = std::move(board_info); }

In the second way I will always create a copy because I am passing by value, but then I move the parameter into the member variable. If I pass an rvalue I do no copying at all, but for an lvalue there will be one copy made always - which I will do any way if I used the first method.

Which of the two methods is recommended? Are rvalue references best used only for constructors and assignment operators?