samedi 31 décembre 2016

Read text file with custom type objects and use istream_iterator?

I need to read in a text file with istream_iterator and seperate it to Customer and Purchase types. Order Objects are defined as (Customer,vector Purchase vP), so every Customer has its own list of Purchases. My problem is that i have to seperate the incoming Order stream to Customer and Purchase Objekt, but the text file has different numbers of Purchases.

//Custom Class Customer,Class Purchase...

class Order {
public:

Order() :
cust(Customer{}), vP(std::vector<Purchase>{}) {
};

Order(Customer c, std::vector<Purchase> v) :
cust{c}, vP{v}
{
    sort(vP.begin(), vP.end());
}

Customer get_cust() const {
    return cust;
}
friend std::ostream& operator<<(std::ostream&, const Order&);
friend std::istream& operator>>(std::istream&, Order&);

// etc.
private:
Purchase pur;
Customer cust;
std::vector<Purchase> vP;
};

ostream& operator<<(std::ostream& out, const Order& o) {
out << o.cust << endl;
for (int i{0}; i < o.vP.size(); i++) {
    out << " " << i + 1 << " " << o.vP.at(i) << endl;
}
return out;
}

// I need help right here... // How can I seperate incoming Objects properly?

istream& operator>>(std::istream& in, Order& o) {

if (in >> o.cust >> o.pur) {
    o.vP.push_back(o.pur);
// I know I have to seperate here...
    return in;
}
}


int main() {

vector<Order> vectOrd;

ifstream inFile("C:\\cpo1.txt");

istream_iterator<Order> eof;
istream_iterator<Order> in_iter(inFile);

    while (in_iter != eof) {
        vectOrd.push_back(*in_iter++);
    }


for (int i{0}; i < vectOrd.size(); i++) {
    cout << "Order: \n" << vectOrd.at(i) << endl;
}

return 0;
}

// This is the Text file that i have to read in

#725454 Schenker Rudolf DE-30159 Hannover
Shirt 135.95 1
Tie 89.59 1
#987654 Orbison Roy US-TN37075 Hendersonville
Mug 1.49 3
T-Shirt 14.90 1
#123456 Petty Tom US-FL32641 Gainesville
Flashlight 12.95 2
#246802 Hite Bob US-CA90291 Venice
CannedBeans 0.89 10
CannedTomatoes 1.79 6
#246802 Hite Bob US-CA90291 Venice
CanOpener 0.48 1
Spoon 1.49 4
Needle 0.05 100
#135791 Lewis Huey US-MT59870 Stevensville
Flux-Compensator 28950.00 1
Comic 1.00 1
BaseballBat 29.00 1
PS4 549.00 1
#725454 Schenker Rudolf DE-30159 Hannover
Yacht 12000000.00 1
LifeSaver 8.95 20
#101112 Cale JJ US-OK73101 Oklahoma-City
Amplifier 534.95 1
Speaker 198.00 4
#555453 Williams Robbie GB-ST01782 Stoke-On-Trent
Radiator 159.00 3
MercedesSLS 264000.00 1
#123124 Waits Tom US-CA91765 Pomona
Banjo 399.00 1
PS4 599.00 1
AudiA8 119500.00 1
#101112 Cale JJ US-OK73101 Oklahoma-City
SpareFuse 0.10 20

// Thanks for every response!

PRNG program failure. Cannot enter random amount of choices and will always answer with 2 from the PRNG

So as the title describes I'm trying to learn PRNG but it hasn't gone too well thusfar. I am writing a program that takes an entered number of choices, rolls a dice and makes the choice for you. I do this using rand() and an array of strings with a length that is dependant on a variable read in before the declaration of the array.

The two problems showing up are that if I try to choose between for example 12 choices, the program will crash. As I read in the length of the array before I declare it I don't understand how this could happen. Also the PRNG will always return the number 2 which is not the desired function of a function that should return a random number between min and max. I will share my code below:

#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()
#include <string>

using namespace std;

int callPRNG(int min, int max)
{
    srand(static_cast<unsigned int>(time(0))); // set initial seed value to system clock

    static const double fraction = 1.0 / (static_cast<double>(RAND_MAX) + 1.0);  // static used for efficiency, so we only calculate this value once
    // evenly distribute the random number across our range
    return static_cast<int>(rand() * fraction * (max - min + 1) + min);
}


int main()
{
    int max=1;
    int min=0;

    cout << "Please enter the amount of choices you want to choose from: ";
    cin >> max;
    string choices[max-1];
    int choiceMade=0;

    {
    int i=0;
        while(i<=max-1)
        {
            cout << "Please enter choice " << i+1 << ": ";
            cin >> choices[i];
            i++;
        }
        choiceMade=callPRNG(min, max-1);
        cout << "I have decided: " << choices[choiceMade-1];
    }

    return 0;
}

As extra information, I'm using code::blocks with C++11 enabled on a windows 10 OS. I hope someone can help me with this as I don't quite understand arrays and PRNG well enough to find the error by myself. Thanks :)

Make file readable only for program

Is there any way in C++ to make file readable only for program without encrypting it? I want to create file which contains few lines of text that program reads, but the user must be unable to read it using simple prog. like "Notepad++".

Move constructor and move assignement operator for class

Im trying to compile the following code for an embedded device (Its a crosscompiler from TI with experimental support of C++11 (C++0)). Target:

arm-arago-linux-gnueabi Thread model: posix gcc version 4.5.3 20110311 (prerelease) (GCC)


The default specifier for the move constructor and move assignement operator cannot be compiled (/home/user/test/main.cpp:40:26: error: 'th& th::operator=(th&&)' cannot be defaulted).

std::make_unique & emplace_back are not implemented, those not usable.

What do I need to change in the code to make it work for this platform?

class th {
    public:
        void func() {
            sleep(3);
            *this->progress = 100;
        }

        th(int* prog) :
            progress(prog), 
            m_thread(std::thread(&th::func, this)) {};

        th(th const& other) = delete;
        th(th && other) = default;
        th& operator=(th const& other) = delete;
        th& operator=(th &&) = default;

        void join() { m_thread.join(); }
        int *progress;

    private:
        std::thread m_thread;
};

int main(void) {

        std::vector<int> progress;
        progress.push_back(-1);
        progress.push_back(-1);

        std::deque<std::unique_ptr<th>> deq;

        std::cout << "progress[0]:" << progress[0] << std::endl;
        std::cout << "progress[1]:" << progress[1] << std::endl;

        std::cout << "executing threads..." << std::endl;

        for(size_t i = 0; i < 2; ++i) {
            deq.push_back(std::unique_ptr<th>(new th(&progress[i])));
        }

        while(true) {
            std::cout << "SIZE:" << deq.size() << std::endl;

            if(deq.size() == 0)
                break;

            for (std::deque<std::unique_ptr<th>>::iterator it = deq.begin(); it != deq.end(); it++) {
                //std::cout << (*it)->progress << std::endl;
                if(*((*it)->progress) == 100) {
                    std::cout << "JOIN & DELETE" << std::endl;
                    (*it)->join();
                    deq.erase(it);
                }
                else {
                    std::cout << "STILL RUNNING" << std::endl;
                }
                    //std::cout << *((*it)->progress) << std::endl;
            }
            sleep(1);
        }

    exit(EXIT_SUCCESS);
}

C++ Repeated do-if-do pattern

I currently have code of the following form:

Do1(A);
if (B != null) Do1(B);

Do2(A, true);
if (B != null) Do2(B, true);

Do3(A);
if (B != null) Do3(B);

So several times, I execute something for object A, and if B is specified, I also do it for B. This means my entire code is duplicated and I would like to change that but I can't come up with a good way to improve this pattern.

The only idea I had so far was something like

auto doBoth = [&A,&B](function<void(const T&)> f) {
  f(A);
  if (B != null) f(B);
};

doBoth(&Do1);
auto do2_bind = [](const T& obj) {Do2(obj, true);};
doBoth(do2_bind);
doBoth(&Do3);

but I feel like that would greatly reduce readability and make it harder for someone to understand my code, as there is this quite abstract lambda function and a lot of lambdas in general.

Is there any way to return three containers in one getter?

I'm wondering is there any way to get access to three containers at once. I have class like :

class DataContainer
{

private:
    std::vector<Rental*> rentals;
    std::vector<Vehicle*> vehicles;
    std::vector<Client*> clients;

public:
    DataContainer();
    bool loadObjects();
    bool createRentals();
    std::string showVehicles() const;
    std::string showClients() const;
    std::string showDetails() const ;
    std::tuple< std::vector<Vehicle*>type1, std::vector<Client*>type2, std::vector<Rental*>type3 > getContainers();
    virtual ~DataContainer();

};

I would like to have possibility to access from other class to these containers, that's why I would like to set some getter, but here comes my problem. I don't know if I'm doing something wrong but the errors I get are :

include\DataContainer.h|74|error: template argument 1 is invalid|
||=== Build failed: 1 error(s), 2 warning(s) (0 minute(s), 1 second(s)) ===|

my function looks like this :

std::tuple< std::vector<Vehicle*>type1, std::vector<Client*>type2, std::vector<Rental*>type3 > DataContainer::getContainers()
{
   return std::make_tuple(vehicles,clients,rentals);
}   

Hope someone will be able to give me some hint, if that makes any difference I'm working on C++11.

std::bind fails to compile with std::atomic_bool& on MSVC


I'm using VC++ to compile my program (using Visual Studio 2015, update 3) and some snippet fails to compile.

basically, I want to bind a function which gets a reference to atomic boolean with atomic boolean. self containing code:

void stub(std::atomic_bool& b) {
    b = true;
}

int main() {
    std::atomic_bool b(false);
    std::function<void()> delegate = std::bind(stub, b); //fails to compile

    auto& ref = b;
    std::function<void()> delegate0 = std::bind(stub, ref); //fails to compile

    std::function<void()> delegate1 = std::bind(stub, std::ref(b)); //compiled
/*...*/
    }

the compiler stack trace:

1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\xutility(357): error C2665: 'std::tuple<std::atomic<bool>>::tuple': none of the 2 overloads could convert all the argument types
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\tuple(608): note: could be 'std::tuple<std::atomic<bool>>::tuple(std::tuple<std::atomic<bool>> &&)'
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\tuple(607): note: or       'std::tuple<std::atomic<bool>>::tuple(const std::tuple<std::atomic<bool>> &)'
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\xutility(357): note: while trying to match the argument list '(std::atomic<bool>)'
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\functional(866): note: see reference to function template instantiation 'std::_Compressed_pair<void (__cdecl *)(std::atomic_bool &),std::tuple<std::atomic<bool>>,false>::_Compressed_pair<void(__cdecl &)(std::atomic_bool &),_Cv_TiD&>(std::_One_then_variadic_args_t,_Other1,_Cv_TiD &)' being compiled
1>          with
1>          [
1>              _Cv_TiD=std::atomic<bool>,
1>              _Other1=void (__cdecl &)(std::atomic_bool &)
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\functional(864): note: see reference to function template instantiation 'std::_Compressed_pair<void (__cdecl *)(std::atomic_bool &),std::tuple<std::atomic<bool>>,false>::_Compressed_pair<void(__cdecl &)(std::atomic_bool &),_Cv_TiD&>(std::_One_then_variadic_args_t,_Other1,_Cv_TiD &)' being compiled
1>          with
1>          [
1>              _Cv_TiD=std::atomic<bool>,
1>              _Other1=void (__cdecl &)(std::atomic_bool &)
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\functional(863): note: while compiling class template member function 'std::_Binder<std::_Unforced,void (__cdecl &)(std::atomic_bool &),std::atomic_bool &>::_Binder(_Fx,std::atomic_bool &)'
1>          with
1>          [
1>              _Fx=void (__cdecl &)(std::atomic_bool &)
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\functional(890): note: see reference to function template instantiation 'std::_Binder<std::_Unforced,void (__cdecl &)(std::atomic_bool &),std::atomic_bool &>::_Binder(_Fx,std::atomic_bool &)' being compiled
1>          with
1>          [
1>              _Fx=void (__cdecl &)(std::atomic_bool &)
1>          ]
1>  c:\visual studio 2015\projects\quantum\quantum\main.cpp(658): note: see reference to class template instantiation 'std::_Binder<std::_Unforced,void (__cdecl &)(std::atomic_bool &),std::atomic_bool &>' being compiled

Is there something I miss or it's the compiler fault?

How to insert a python code in C++?

i am trying to embed a code python in c++. I have this python code :

#include <Python.h>

int main(int arg){
Py_SetProgramName(argv[0]);
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"

                     "print 'Today is',ctime(time())\0");
Py_Finalize();
return 0;
}

but what i want is something like that :

include

int main(int arg){
Py_SetProgramName(argv[0]);
int a = 5;
Py_Initialize();
PyRun_SimpleString("a = "+a);
Py_Finalize();
return 0;
}

but it does not work. I mean i want with python to display the value of the variable a. Thank you :)

mingw32-g++: 'std::tr1' has not been declared

I'm facing this issue using Code::Blocks 16.01, everything works perfectly in Visual Studio 2015. The compiler option "Have g++ follow the C++11 ISO C++ language standard [-std=c++11]" is enabled, and the build log is:

mingw32-g++.exe -Weffc++ -std=c++11 -g  -c "<path>\heuristic.cpp" -o .objs\heuristic.o
In file included from <path>\METSlib\metslib-0.5.3\metslib\mets.hh:129:0,
                 from <path>\Model.h:2,
                 from <path>\<file>,
                 from <path>\<file>:
<path>\METSlib\metslib-0.5.3\metslib\model.hh: In function 'void mets::random_shuffle(mets::permutation_problem&, random_generator&)':
<path>\METSlib\metslib-0.5.3\metslib\model.hh:252:10: error: 'std::tr1' has not been declared
     std::tr1::uniform_int<size_t> unigen;

followed by lots of other errors, all related to the missing std::tr1 library. (I've replaced some paths and files with placeholders for privacy)

What am I missing in the compiler configuration?enter image description here

Why does the C++ standard specifically grant leeway regarding memory layout of class data members with different access specifiers?

The C++11 standard mandates an ordering in memory for the non-static data members of a class but then specifically carves out an exemption for members with different access specifiers.

Why though?

§ 9.2.13

Nonstatic data members of a (non-union) class with the same access control (Clause 11) are allocated so that later members have higher addresses within a class object. The order of allocation of non-static data members with different access control is unspecified (Clause 11). Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions (10.3) and virtual base classes (10.1).

This part of the standard has come up on stackoverflow before but I don't think it has ever been explained.

Do I need to install Boost to build odeint?

Can I directly download the odeint files from odeint website and build it from there without installing the whole boost libraries?

i.e. only download the odeint from the following website http://ift.tt/2imNVDw or Github link http://ift.tt/14ZI2DM

I have found tons of instructions on installing boost and used their great libraries. Now we only need the odeint for my current project. Can I only download the odeint library and built it from there without download & build & install the whole boost libraries from the boost website?

I can't find any odeint document to explain it.Your help is appreciated.

Is atomic_compare_exchange_weak preferable over the strong version even in a long loop?

Suppose I use CAS inside a loop that contains a number of operations other than the CAS. The loop runs until the CAS succeeds. Should I use the weak version of CAS? Or will it be non cost effective to redo all the loop's operations in case the CAS spuriously fail, and I'd better use the strong version of CAS to ensure repeating the loop only if the CAS really had to fail (because object != expected)? Or is there no theoretical answer and I should try both versions and compare their performance?

How to 'new' a stucture using another pointer inside a differnt structure

I have a code like this: struct Pass { string fname , lname; };

struct T {
    Pass* p;
};

int main(int argc, char** argv) {
    T* t;
    t = new T[5];
    t[4].p = new Pass [3];
    return 0;
}

When I run it, STOP WORKING was only result; no errors, no text in console. OS Win7 / IDE Codelite / Debugger GNU gdb

vendredi 30 décembre 2016

how to delete adjacent entries from a set while iterating over it

How can I erase all adjacent entries from a set while iterating over the set. In my case I have a custom comparator that defines adjacent entries as those that differ by 1 from left to right. Thus for the set std::set<int> mySet = {1,2,3,4,5,7,9,10} I would like to remove the entries {1,2,3,4,5,9,10} as these satisfy my comparator. (note the 7 is left as it is the only one in the series is not one of the elements in an adjacent pair.

The code below (also in coliru) shows that I can find add the adjacent entries correctly, however if I try to erase both the left side of the adjacent pair adjIter and also the right side *std::next(adjIter) the code crashes with an invalid iterator.

int main() {    
    std::set<int> mySet = {1,2,3,4,5,7,9,10};
    static const auto gPred = [](const auto& lhs, const auto& rhs) {
        return rhs == lhs+1;
    };
    auto adjIter = mySet.begin();
    std::set<int> adjacentEntries;
    while ((adjIter = std::adjacent_find(adjIter, mySet.end(),
        gPred)) != mySet.end()) {
        adjacentEntries.insert(*adjIter);
        // peek at the second entry that should be 1 greater than adjIter        
        adjacentEntries.insert(*std::next(adjIter));
        // how do I erase both *std::next(adjIter) & adjIter
        ++adjIter;
    }
    std::cout << adjacentEntries << std::endl;
}

How can I know if I need to delete something in C++?

Imagine the following class:

class MyString {
public:
    const char* str;
    std::size_t str_len;

    MyString(const char* str, std::size_t str_len)
        : str { str }
        , str_len { str_len }
    {}
}

I'm a bit confused about implementing a destructor for MyString. My first thought was that it would look like this:

~MyString() {
    delete [] str;
}

But how can I delete str if I can't be sure that it was allocated? For example, I could create an instance of MyString like this:

const char* c_string = "Hello, World!";
MyString my_string(c_string, 13);

in which case I shouldn't delete str because it was not declared on the heap, but if I created an instance of MyString like this:

char* char_array = new char[13]{'H','e','l','l','o',',',' ','W','o','r','l','d','!'};
MyString my_string(char_array, 13);

not deleting str would cause a memory leak (I assume) because it would be declared on the heap. But if I created an instance of MyString like this:

char* char_array = new char[13]{'H','e','l','l','o',',',' ','W','o','r','l','d','!'};
MyString my_string(char_array + 3, 10);

I shouldn't delete str because although it's on the heap, it hasn't been allocated; it just points to part of something else that's been allocated.

So how can I be sure that I'm not deleting something that I shouldn't be deleting or failing to delete something that needs to be deleted? Would the answer be different if MyString used char*s instead of const char*s? What if I used MyString my_string = new MyString...?

How to use functions with different parameters as a function parameter

The title may be a bit confusing, so I will explain it more clearly.

I have a class like:

class foo
{
public:

   foo(%Some function% *) { %Some function pointer% = %Some function%; }

   %Some output% callFunction(%Some input%);

private:

   %Some function pointer% bar;
}

Preferably, I would like to be able to store the given function in "%Some function pointer%" to be used throughout the class, but this isn't necessary.

So my main question is: How could I create a real "callFunction" that can take in any function as an input, along with that functions parameters?

Any help is appreciated!

C++: loop a std::unordered_map, the sequence is always the sequence I insert elements?

I constructed a std::unordered_map and use for loop to visit it. I found that the sequence of the iteration result shows the elements is put in the sequence that I created those elements, no matter how I inserted them.

Is this part of C++ standard that unordered_map, when visited, the iteration sequence is the insertion sequence? Or this is implementation preference?

I ask this question is, I wish to know if this feature, is something I can rely in my c++ code?

Issue Playing Video using OpenCV C++

So I am trying to make OpenCV play the Megamind.avi video, but everytime I run my code it gives me this error:

2016-12-29 19:07:39.916 process[17091:382843] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
*** First throw call stack:
(
    0   CoreFoundation                      0x00007fff92e800db __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x00007fffa7b12a2a objc_exception_throw + 48
    2   CoreFoundation                      0x00007fff92d9c4fb -[__NSArrayM objectAtIndex:] + 203
    3   libopencv_highgui.2.4.dylib         0x000000010b2f0270 _ZN13CvCaptureFileC2EPKc + 350
    4   libopencv_highgui.2.4.dylib         0x000000010b2eece2 _Z32cvCreateFileCapture_AVFoundationPKc + 34
    5   libopencv_highgui.2.4.dylib         0x000000010b2e27de cvCreateFileCapture + 14
    6   libopencv_highgui.2.4.dylib         0x000000010b2e2a8e _ZN2cv12VideoCapture4openERKNSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEE + 64
    7   libopencv_highgui.2.4.dylib         0x000000010b2e28ee _ZN2cv12VideoCaptureC2ERKNSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEE + 42
    8   process                             0x000000010adcd517 main + 215
    9   libdyld.dylib                       0x00007fffa83f4255 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Abort trap: 6

It also occurs whenever I run the sample OpenCV video reading and writing program, so I'm not sure if something is screwed up on my end or has there been a change in OpenCV that broke some methods. Here is my code for reference:

#include <stdio.h>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main()
{
  const string source = "Megamind.avi";
  VideoCapture inputVideo(source);
  if (!inputVideo.isOpened())
  {
    cout  << "Could not open the input video" << source << endl;
    return -1;
  }
  cout  << "read!" << endl;
  namedWindow("Video",1);
  for(;;){
      Mat frame;
      inputVideo >> frame; // get a new frame from camera
      imshow("Video", frame);
      if(waitKey(30) >= 0) break;
  }
  VideoWriter outputVideo;
  return 0;
}

Also if I apply the program to the vtest.avi video file from the same github repo, it returns this error.

OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file /tmp/opencv-20161020-7399-1yrk4nm/opencv-2.4.13.1/modules/highgui/src/window.cpp, line 261
libc++abi.dylib: terminating with uncaught exception of type cv::Exception: /tmp/opencv-20161020-7399-1yrk4nm/opencv-2.4.13.1/modules/highgui/src/window.cpp:261: error: (-215) size.width>0 && size.height>0 in function imshow

I read up online to add this if statement in the for loop:

if (!frame.empty()) {
      imshow("window", frame);
}

but it results in just an empty window. Not sure if this changes my issue at all.

Creating a class to store threads and calling them

Here is a simplified version of what I am trying to do:

#include <iostream>
#include <vector>
#include <thread>
#include <mutex>

class client {
public:
    client() {
        running = true;

        threads.push_back(std::thread(this->main, this));
        threads.push_back(std::thread(this->render, this));
    }

    ~client() {};
protected:
private:
    std::vector<std::thread> threads;
    std::mutex mtx;
    bool running;

    void main() {
        while(running) {
            mtx.lock();
            std::cout << "main" << std::endl;
            mtx.unlock();
        }
    }

    void render() {
        while(running) {
            mtx.lock();
            std::cout << "render" << std::endl;
            mtx.unlock();
        }
    }
};


int main() {
    client c;

    return 0;
}

In fact it actually starts to work, for a couple iterations and then it just crashs.


What I am trying to do is create a class that holds threads for the main loop(of the class), rendering, and a couple other things. However I cannot get this simplified version to work. I have tried using mutex to lock and unlock the threads, but didn't seem to help any. I do not know why it is not working, but I suspect that it is a result of the use of this in threads.push_back(std::thread(this->main, this));.

The current structure of the code doesn't have to remain... The only requirement is that uses one of it's own member functions as a thread (and that, that thread is stored in the class). I am not sure if this requires two classes or if my attempt to do it in one class was the correct approach. I have seen many examples of creating an object, and then calling a member that creates threads. I am trying to avoid this and instead create the threads within the constructor.

Side question: the output to the console doesn't always run as expected, I figured mutex would be the solution, yet the resulting code was unsatisfactory.

Dangerous implicit conversion in emplace

The following code compiles without any errors/warnings with gcc 6.3 (http://ift.tt/2iOknSQ), but it contains a dangerous undefined behavior due to invalid memory access marked below. The root cause is the implicit conversion performed in emplace_back. Can anyone suggest a good way or best practices to avoid such bugs in code?

#include <iostream>
#include <vector>

struct Foo
{
  explicit Foo(const int& i) : i{i} {}

  void foo() const { std::cout << i; }  // invalid memory access, as i is an invalid ref!!
  const int& i;
};

void bar(const double& d) {
  std::vector<Foo> fv;
  fv.emplace_back(d);
}

Gtest, equals object

I want equals 2 objects, exactly cards (unit test with gtest). This is my code:

   #include "stdafx.h"
#include <gtest\gtest.h>
#include <vector>

class Card {
public:
    Card(int value, int color) :value(value), color(color) {};
    int returnColor() const { return color; };
    int returnValue() const { return value; };
    bool operator==(const Card &card) {
        return returnValue() == card.returnValue();
    };
private:
    int value;
    int color;
};

class CardTest : public ::testing::Test {
protected:
    std::vector<Card> cards;
    CardTest() { cards.push_back(Card(10, 2));
    cards.push_back(Card(10, 3));
    };
};
TEST_F(CardTest, firstTest)
{
    EXPECT_EQ(cards.at(0), cards.at(1));
}
int main(int argc, char *argv[])
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

I have error:

State Error C2678 binary '==': no operator found which takes a left-hand operand of type 'const Card' (or there is no acceptable conversion)

I try overload operator '==', but this not working :/ Maybe, I must go other way? This is my first unit test :D.

Element-wise multiplication in 2D vectors in C++11

I am trying to do element-wise multiplication (.*) between two 2D vectors in C++11 using the code below but I am getting the errors as Error C2664 'int std::multiplies::operator ()(const _Ty &,const _Ty &) const' : cannot convert argument 1 from 'std::vector>' to 'const int &' I could not figure out what the actual problem is?

The code I used is as follows

// Example program
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <iterator> 

int main()
{
    std::vector<std::vector<int32_t>> Route = { { 1,2 },{ 3,4 } };
    std::vector<std::vector<int32_t>> Spectrum = { { 2,2 },{ 3,3 } };

    std::vector<std::vector<int32_t>> score;

    //and do element-wise multiplication of Spectrum and Route i.e. Spectrum .* Route
    std::transform(Spectrum.begin() + 1, Spectrum.end(), Route.begin() + 1, std::back_inserter(score), std::multiplies<int32_t>());

    std::vector< std::vector<int32_t> >::iterator row;
    std::vector<int32_t>::iterator col;
    for (row = score.begin(); row != score.end(); row++) {
        for (col = row->begin() + 1; col != row->end(); col++) {
            std::cout << *col << std::endl;
        }
    }
}

std::unique_ptr and QObject::deleteLater

I would like my std::unique_ptr to call QObject::deleteLater to destruct the object.

I can't figure out how to do it.

Nothing I tried compiles.

E.g.

std::unique_ptr<SomeQObject, decltype(&QObject::deleteLater)> var(
                pointer, &QObject::deleteLater);

Please help...

What is the difference between these two approaches?

class A
{
   int a = 100;
};

and

class A
{
    int a;
public :
   A()
   {
      a = 100;
   }
};

I know that there are two approaches because static variables are initialised outside the class and cant that cant be done inside the class. But what difference does it make if i initialise the variable a ( a normal int ) using the constructor or during the declaration itself.

C++11 shared ptr in unordered map not taking new value

I got a minor problem with my unordered_map and I didn't found a "real" solution to it so I am asking all of you here for advice because either I'm derpin or I do something really wrong.

First, here's the precious code:

struct RedirectInfo 
{
    RedirectInfo(AMX_NATIVE hf) { this->orig_func = 0x0; this->hooked_func = hf; }

    AMX_NATIVE orig_func;
    AMX_NATIVE hooked_func;
};
std::unordered_map<std::string, std::shared_ptr<Natives::RedirectInfo>> redirected_natives;

I populate the map the following way:

const char *szNative = "somenative";
redirected_natives[szNative] = std::make_shared<RedirectInfo>(func);

Now.. I'm just using ::find to look if there's an entry and if I do some stuff... There's that code:

const char *szFuncName = "somenative";
auto it = redirected_natives.find(szFuncName);
if (it != redirected_natives.end())
{
    it->second->orig_func = (AMX_NATIVE)0xDEAD; // that's also the problem ->orig_func doesn't get set!
}

So by getting the pointer to the "RedirectInfo" info I already found out that the object in the code above is located at 472cf0 but if I try to access the object with this code:

const char *szName = "somenative";
printf("%x", redirected_natives[szName]->orig_func) // <- returns 0 instead of 0xDEAD

then the value is like I said 0 and the object is offset by +4 / -4 and that's the weird part It seems like I'm accessing some other address space even tho it fetches the right values f.e. hooked_func.

I hope I explained my problem well enough for you guys. Have a nice day, and thank you in advance!

Variadic template not working with an initializer list

I created a factory function template:

template <typename M, typename... Args>
std::shared_ptr<M> create(Args... args)
{
    return std::make_shared<M>(args...);
}

And a simple container:

struct Group {
    std::vector<int> vec;
    Group(std::initializer_list<int> il) : vec(il) {}
};

Then I try to create a Group

int main()
{
    auto gr = create<Group>({1, 2, 3});
    return 0;
}

This doesn't compile,

error: no matching function for call to 'create'
    auto gr = create<Group>({1, 2, 3});
candidate function not viable: requires 0 arguments, but 1 was provided
std::shared_ptr<M> create(Args... args)
                   ^

but if I use a temporary variable:

int main(int argc, char *argv[])
{
    std::initializer_list<int> il = {1, 2, 3};
    auto gr = create<Group>(il);
    return 0;
}

it does. Why?

Performance issues in joining threads

I wrote the following parallel code for examining all elements in a vector of vector. I store only those elements from vector<vector<int> > which satisfy a given condition. However, my problem is some of the vectors within vector<vector<int> > are pretty large while others are pretty small. Due to which my code takes a long time to perform thread.join(). Can someone please suggest as to how can I improve the performance of my code.

void check_if_condition(vector<int>& a, vector<int>& satisfyingElements)
{
    for(vector<int>::iterator i1=a.begin(), l1=a.end(); i1!=l1; ++i1)
        if(some_check_condition(*i1))
            satisfyingElements.push_back(*i1);

}

void doWork(std::vector<vector<int> >& myVec, std::vector<vector<bool> >& results, size_t current, size_t end)
{
    end = std::min(end, myVec.size());
    int numPassed = 0;
    for(; current < end; ++current) {
        vector<int> satisfyingElements;
        check_if_condition(myVec[current], satisfyingElements); 
        if(!satisfyingElements.empty()){
            results[current] = satisfyingElements;            
        }
    }    
}

int main()
{
    std::vector<std::vector<int> > myVec(1000000);
    std::vector<std::vector<bool> > results(myVec.size());   
    unsigned numparallelThreads = std::thread::hardware_concurrency();

    std::vector<std::thread> parallelThreads;
    auto blockSize = myVec.size() / numparallelThreads;
    for(size_t i = 0; i < numparallelThreads - 1; ++i) {
        parallelThreads.emplace_back(doWork, std::ref(myVec), std::ref(results), i * blockSize, (i+1) * blockSize);
    }

    //also do work in this thread
    doWork(myVec, results, (numparallelThreads-1) * blockSize, myVec.size());

    for(auto& thread : parallelThreads)
        thread.join();

    std::vector<int> storage;
    storage.reserve(numPassed.load());

    auto itRes = results.begin();
    auto itmyVec = myVec.begin();
    auto endRes = results.end();
    for(; itRes != endRes; ++itRes, ++itmyVec) {
        if(!(*itRes).empty)
            storage.insert(storage.begin(),(*itRes).begin(), (*itRes).end());
    }

    std::cout << "Done" << std::endl;
}

Vector of vector vs Vector

In C++11, how does vector(outer) of vector (inner) (2D) performs against 1D vector in terms of time?
In the 2D vector given, all the inner vectors are of the same size.

Ex: std::vector> X{10, std::vector(4)};
vs
std::vector Y(40);

Which avatar of the vector would perform better When the elements are randomly accessed?

How to static_assert that an initializer list is a certain size

Would it be possible to verify that an initializer list that is being passed to a constexpr constructor is a certain size? Or would this only be possible to do at runtime?

This is the idea, but it doesn't work:

struct group
{
        constexpr group(
            std::initializer_list<std::initializer_list<UINT const> const> groups
        )
        {
            static_assert(each_list_size_greater_than_1(groups.begin(), groups.end()));
        }

        constexpr static bool each_list_size_greater_than_1(
            std::initializer_list<std::initializer_list<UINT const> const>::const_iterator const begin
            , std::initializer_list<std::initializer_list<UINT const> const>::const_iterator const end)
        {
            return begin == end || begin->size() > 1 && each_list_size_greater_than_1(begin + 1, end);
        }
};

I've looked at VS2015's std::initializer_list implementation and begin(), end() and size() are all constexpr functions.

Append to std::array

Since I was not able to find such a function (incorrectly?), I'm trying to make a compile-time function (constexpr) function which takes a std::array<T,n> arr and a T t and returns a new std::array<T,n+1> with t added to the end of arr. I've started with something like this:

template <typename T, int n>
constexpr std::array<T,n+1> append(std::array<T,n> a, T t);

template <typename T>
constexpr std::array<T,1> append(std::array<T,0> a, T t)
{
  return std::array<T,1>{t};
}

template <typename T>
constexpr std::array<T,2> append(std::array<T,1> a, T t)
{
  return std::array<T,2>{a[0], t};
}

Here I get stuck. What I need is a way to expand a in the first n places of the initializer list, and then add t add the end. Is that possible? Or is there another way of doing this?

Compile time array indexing using expression templates -- constexpr?

I want to generate a function like this:

double apply_stencil(const double *u, const int i, const width,
                     const int *offset, const double *weight)
{
  double t=0;
  for(int j=0; j<width; j++)
    t += u[i+offset[j]] * weight[j];
  return t;
}

But I want to make sure that the width, the offsets, and possibly even the weights are compile/time constants.

That is possible to achieve by defining a type:

template <typename S>
double apply_stencil(const double *u, const int i)
{
  double t=0;
  for(int j=0; j<S::width; j++)
    t += u[i+S::offset[j]] * S::weight[j];
  return t;
}

// then:
struct Stencil {
  const static double weight[];
  const static int offset[];
  const static unsigned int width = 3;
};

const double Stencil::weight[] = {1.0, 2.0, 1.0};
const int Stencil::offset[]    = {-1, 0, 1};

However, this is not very pretty. I want a user to be able to specify the Stencil in their application code, and then call my apply_stencil function from my header file (this is really a simplification of something much more complicated).

Ideally, I would like to have the thing specified using expression templates, like so:

const Symbol u;
const Stencil<3> s (1*u[-1] + 2*u[0] + 1*u[1]);

Which uses this infrastructure:

struct Accessor {
  int offset;
};

struct Symbol
{
  Accessor operator[](int i) const {
    return Accessor{i};
  }
};

struct WeightedTerm
{
  double weight;
  int offset;
  WeightedTerm()
    : weight(1), offset(0) {}

  WeightedTerm(double a, Accessor u)
    : weight(a), offset(u.offset) {}
};

WeightedTerm operator*(double a, Accessor u) {
  return WeightedTerm(a,u);
}

template <int n>
struct Sum
{
  WeightedTerm terms[n];

  Sum(WeightedTerm x, WeightedTerm y) {
    terms[0] = x;
    terms[1] = y;
  }

  Sum(Sum<n-1> x, WeightedTerm y) {
    for(int i = 0; i < n-1; ++i)
      terms[i] = x.terms[i];

    terms[n-1] = y;
  }
};

Sum<2> operator+(WeightedTerm x, WeightedTerm y) {
  return Sum<2>(x,y);
}

template <int n>
Sum<n+1> operator+(Sum<n> x, WeightedTerm y) {
  return Sum<n+1>(x,y);
}

template <int width>
struct Stencil
{
  double weights[width];
  int offsets[width];
  Stencil(const Sum<width> s) {

    for(int j = 0; j < width; ++j) {
      weights[j] = s.terms[j].weight;
      offsets[j] = s.terms[j].offset;
    }
  };
};

This looks nice, but now, the arrays are not necessarily compile time known. If I write it like I do above with literals in the expression, I have verified that the compiler can make the correct optimizations. But I want to make find a way to guarantee that they are always compile time constants.

I presume I could encode the offset as a template parameter in Accessor and WeightedTerm, but I can't see how I could do that and keep the desired expression syntax since operator() takes the offset as a regular argument.

So, the question is if there is a way to achieve this? I have a feeling that constexpr could be of use here which I am a bit unfamiliar with.

Having Trouble Playing Video Through OpenCV C++

So I am trying to make OpenCV play the Megamind.avi video for me, but everytime I run my code it gives me this error:

2016-12-29 19:07:39.916 process[17091:382843] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
*** First throw call stack:
(
    0   CoreFoundation                      0x00007fff92e800db __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x00007fffa7b12a2a objc_exception_throw + 48
    2   CoreFoundation                      0x00007fff92d9c4fb -[__NSArrayM objectAtIndex:] + 203
    3   libopencv_highgui.2.4.dylib         0x000000010b2f0270 _ZN13CvCaptureFileC2EPKc + 350
    4   libopencv_highgui.2.4.dylib         0x000000010b2eece2 _Z32cvCreateFileCapture_AVFoundationPKc + 34
    5   libopencv_highgui.2.4.dylib         0x000000010b2e27de cvCreateFileCapture + 14
    6   libopencv_highgui.2.4.dylib         0x000000010b2e2a8e _ZN2cv12VideoCapture4openERKNSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEE + 64
    7   libopencv_highgui.2.4.dylib         0x000000010b2e28ee _ZN2cv12VideoCaptureC2ERKNSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEE + 42
    8   process                             0x000000010adcd517 main + 215
    9   libdyld.dylib                       0x00007fffa83f4255 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Abort trap: 6

It also occurs whenever I run the sample OpenCV video reading and writing program, so I'm not sure if something is screwed up on my end or has there been a change in OpenCV that broke some methods. Here is my code for reference:

#include <stdio.h>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main()
{
  const string source = "Megamind.avi";
  VideoCapture inputVideo(source);
  if (!inputVideo.isOpened())
  {
    cout  << "Could not open the input video" << source << endl;
    return -1;
  }
  cout  << "read!" << endl;
  namedWindow("Video",1);
  for(;;){
      Mat frame;
      inputVideo >> frame; // get a new frame from camera
      imshow("Video", frame);
      if(waitKey(30) >= 0) break;
  }
  VideoWriter outputVideo;
  return 0;
}

Also if I apply the program to the vtest.avi video file in the same github repo, it returns this error.

OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file /tmp/opencv-20161020-7399-1yrk4nm/opencv-2.4.13.1/modules/highgui/src/window.cpp, line 261
libc++abi.dylib: terminating with uncaught exception of type cv::Exception: /tmp/opencv-20161020-7399-1yrk4nm/opencv-2.4.13.1/modules/highgui/src/window.cpp:261: error: (-215) size.width>0 && size.height>0 in function imshow

I read up online to add this if statement in the for loop:

if (!frame.empty()) {
      imshow("window", frame);
}

but there results in just an empty window. Not sure if this changes my issue at all.

Nvidia physX destructible moving and removing chunks independently

Is there a way around nvidia apex destructible api to remove individual chunks and set transforms and velocities of the chunks.

In other words I want to have manual intervention and control on how the individual chunks behave.

There is a set velocity and set location/rotation function in NxDestructibleActor but it applies to all chunks not just one

Can you please tell me how to use boost logger in c++ , provide sample application

I am new to c++ 11 concepts, please provide sample application with boost log

Class-typed static constexpr field giving link-time errors in g++

I have this snippet of code I was testing today:

#include <iostream>

struct Literal {
    constexpr operator int() const { return 0; }
};

struct Class {
    constexpr static const Literal field0 = Literal();
};

int main(void) {
    std::cout << "Class::field0: " << Class::field0 << std::endl;
    return 0;
}

It compiles without errors (G++ 6.2.1), but unfortunately I get a link error when generating the executable:

/tmp/ccao6eTy.o: In function `main':
test-constexpr-static-field.cpp:(.text+0xa): undefined reference to `Class::field0'
collect2: error: ld returned 1 exit status
[Finished in 0.3s with exit code 1]

Reading this page I see this explanation:

If a static data member of LiteralType is declared constexpr, it must be initialized with an initializer in which every expression is a constant expression, right inside the class definition (...).

Then I went for the definition of what is a LiteralType, and I saw that:

A literal type is any of the following:

  • possibly cv-qualified class type that has all of the following properties:
    • has a trivial destructor,
    • is either
    • an aggregate type,
    • a type with at least one constexpr (possibly template) constructor that is not a copy or move constructor,
    • a closure type (since C++17)
  • all non-static data members and base classes are of non-volatile literal types.

Is it the case that Literal does not conform to a LiteralType? As I see it, it has a trivial constructor, and even has no internal state to avoid any troublesome issue with aggregate types or non-static fields on a literal type.

But considering it does conform (primarily because the program compiled without errors), why the link-time error? Is that a G++ bug, perhaps?

Remove union large vectors in c++ efficiently?

I need to union a million vectors for doing so I am using the following program. Each of the vectors contain a billion elements. The result of the union should not contain any duplicates.

set<unsigned> myfunc()
{
    vector<unsigned> vec(1000000); 
    set<unsigned> result;
    for(int i=0; i<1000000; i++)
       result.insert(vec[i].begin(), vec[i].end(); //vec[i] contains a billion elements

    return result;
}

Is there some way by which I may union the two large vectors effectively? As the above code seems to be running

How does the control block of a shared pointer behave with const shared pointers

const std::shared_ptr<int> x (new int (2));
const std::shared_ptr<int> y (x);

copying a shared pointer makes changes to the control block where the 'const' shared pointers point to, does that not contradict the constness part?

C++ condition_variable wait_for returns instantly

This is simple code from http://ift.tt/1ybekE3

Why does wait_for() return instantly if I comment line with starting thread?

Like this:

// condition_variable::wait_for example
#include <iostream>           // std::cout
#include <thread>             // std::thread
#include <chrono>             // std::chrono::seconds
#include <mutex>              // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable, std::cv_status

std::condition_variable cv;

int value;

void read_value() {
  std::cin >> value;
  cv.notify_one();
}

int main ()
{
  std::cout << "Please, enter an integer (I'll be printing dots): ";
  //std::thread th (read_value);

  std::mutex mtx;
  std::unique_lock<std::mutex> lck(mtx);
  while (cv.wait_for(lck,std::chrono::seconds(1))==std::cv_status::timeout) {
    std::cout << '.';
  }
  std::cout << "You entered: " << value << '\n';

  //th.join();

  return 0;
}

Parameter pack expansion doesn't work

I tried to make multiplex of std::set, named NDos::set_multiplex, which can view the elements in perspective of various comparison objects. For example, a set of playing cards could be sorted with rank first and suit second, or suit first and rank second; NDos::set_multiplex enables to do this conveniently. NDos::set_multiplex does this by inheriting multiple std::sets, one storing the elements, and the others storing the iterator to the elements. NDos::IterComp is a Callable type that compares the elements refered by two iterators.

Here is the full code:

#ifndef SET_MULTIPLEX_H_INCLUDED
#define SET_MULTIPLEX_H_INCLUDED
#include <iterator>
#include <utility>
#include <memory>
#include <set>
#include "Iter.h"
namespace NDos {
    template <class T, class Comp0, class... Comps> class set_multiplex :
        private std::set<T, Comp0>,
        private std::set<
            typename std::set<T, Comp0>::iterator,
            IterComp<typename std::set<T, Comp0>::iterator, Comps>
        >... {
    private:
        typedef std::set<T, Comp0> Base0;
    public:
        using typename Base0::value_type;
        using typename Base0::allocator_type;
        using typename Base0::size_type;
        using typename Base0::difference_type;
        using typename Base0::reference;
        using typename Base0::const_reference;
        using typename Base0::pointer;
        using typename Base0::const_pointer;
        using typename Base0::iterator;
        using typename Base0::const_iterator;
        using typename Base0::reverse_iterator;
        using typename Base0::const_reverse_iterator;
#define Bases std::set<iterator, IterComp<iterator, Comps>>
        explicit set_multiplex(const Comp0 &comp0 = Comp0(), const Comps &...comps) : Base0(comp0),
            Bases(IterComp<iterator, Comps>{comps})... {}
        template <class InputIt> set_multiplex(InputIt first, InputIt last, const Comp0 &comp0 = Comp0(), const Comps &...comps)
        : set_multiplex(comp0, comps...) {
            insert(first, last);
        }
        set_multiplex(std::initializer_list<T> ilist, const Comp0 &comp0 = Comp0(), const Comps &...comps)
        : set_multiplex(std::make_move_iterator(ilist.begin()), std::make_move_iterator(ilist.end()), comp0, comps...) {}
        // copy constructor : default
        // move constructor : default
        // copy assignment operator : default
        // move assignment operator : default
        // destructor : default
        using Base0::get_allocator;
        using Base0::begin;
        template <class C> auto begin() noexcept {
            return std::set<iterator, IterComp<iterator, C>>::begin();
        }
        template <class C> auto begin() const noexcept {
            return std::set<iterator, IterComp<iterator, C>>::begin();
        }
        using Base0::cbegin;
        template <class C> auto cbegin() const noexcept {
            return std::set<iterator, IterComp<iterator, C>>::cbegin();
        }
        using Base0::end;
        template <class C> auto end() noexcept {
            return std::set<iterator, IterComp<iterator, C>>::end();
        }
        template <class C> auto end() const noexcept {
            return std::set<iterator, IterComp<iterator, C>>::end();
        }
        using Base0::cend;
        template <class C> auto cend() const noexcept {
            return std::set<iterator, IterComp<iterator, C>>::cend();
        }
        using Base0::rbegin;
        template <class C> auto rbegin() noexcept {
            return std::set<iterator, IterComp<iterator, C>>::rbegin();
        }
        template <class C> auto rbegin() const noexcept {
            return std::set<iterator, IterComp<iterator, C>>::rbegin();
        }
        using Base0::crbegin;
        template <class C> auto crbegin() const noexcept {
            return std::set<iterator, IterComp<iterator, C>>::crbegin();
        }
        using Base0::rend;
        template <class C> auto rend() noexcept {
            return std::set<iterator, IterComp<iterator, C>>::rend();
        }
        template <class C> auto rend() const noexcept {
            return std::set<iterator, IterComp<iterator, C>>::rend();
        }
        using Base0::crend;
        template <class C> auto crend() const noexcept {
            return std::set<iterator, IterComp<iterator, C>>::crend();
        }
        using Base0::empty;
        using Base0::size;
        using Base0::max_size;
        void clear() noexcept {
            Base0::clear();
            /*Bases::clear()...;*/
        }
        iterator insert(const T &value) {
            return emplace(value);
        }
        iterator insert(T &&value) {
            return emplace(std::move(value));
        }
        iterator insert(const_iterator pos, const T &value) {
            return emplace_hint(pos, value);
        }
        iterator insert(const_iterator pos, T &&value) {
            return emplace_hint(pos, std::move(value));
        }
        template <class InputIt> void insert(InputIt first, InputIt last) {
            while (first != last)
                insert(*first++);
        }
        void insert(std::initializer_list<T> ilist) {
            insert(std::make_move_iterator(ilist.begin()), std::make_move_iterator(ilist.end()));
        }
        template <class... Args> iterator emplace(Args &&...args) {
            iterator i0 = Base0::emplace(std::forward<Args>(args)...).first;
            /*Bases::insert(i0)...;*/
            return i0;
        }
        template <class... Args> iterator emplace_hint(const_iterator pos, Args &&...args) {
            iterator i0 = Base0::emplace_hint(pos, std::forward<Args>(args)...).first;
            /*Bases::insert(i0)...;*/
            return i0;
        }
        iterator erase(iterator pos) {
            /*Bases::erase(pos)...;*/
            return Base0::erase(pos);
        }
        iterator erase(const_iterator first, const_iterator last) {
            while (first != last)
                erase(first++);
        }
        size_type erase(const T &key) {
            iterator pos = find(key);
            if (pos == end())
                return 0;
            else {
                erase(pos);
                return 1;
            }
        }
        void swap(set_multiplex &other) noexcept {
            Base0::swap(other);
            /*Bases::swap(other)...;*/
        }
        using Base0::count;
        using Base0::find;
        using Base0::lower_bound;
        using Base0::upper_bound;
        using Base0::equal_range;
        using Base0::key_comp;
        template <class C> auto key_comp() const {
            return std::set<iterator, IterComp<iterator, C>>::key_comp().comp;
        }
        using Base0::value_comp;
        template <class C> auto value_comp() const {
            return std::set<iterator, IterComp<iterator, C>>::value_comp().comp;
        }
        friend void swap(set_multiplex &a, set_multiplex &b) noexcept {
            a.swap(b);
        }
#undef Bases
    };
}
#endif // SET_MULTIPLEX_H_INCLUDED

The commented expressions are the problem. The parameter packs aren't expanded properly. G++ 6.2 reports those errors each expansion:

error: expected ';' before '...' token
error: parameter packs not expanded with '...'

Why do these happen?

jeudi 29 décembre 2016

How to make implicit conversion constructor call over 2 class in C++?

Here is the test code:

class A 
{
public:
    A(const int& i){}
};

class B
{
public:
    B(const A& a) {};
};


int main() 
{
    B b = 1;
    return 0;
}

It comes to error: "No viable conversion from int to B".

It's obviously that int can be converted to B through being converted to A. But it seems that C++ does not search the constructor inherited tree.

Note that B is not inherited from A.

Is there any way to make it possible without adding a int constructor for B manually?

Always prefer [std::bind(&A::mem_fn, &obj)] to [std::bind(&A::mem_fn, obj)]?

#include <functional>

struct A
{
    A() = default;
    A(const A&) = delete;
    A& operator =(const A&) = delete;

    void foo() const
    {}
};

int main()
{
    A a;
    std::bind(&A::foo, &a); // ok
    std::bind(&A::foo, a);  // error

    return 0;
}

The example seems to say:

You should always prefer std::bind(&A::foo, &a); to std::bind(&A::foo, a);.

More serious, if copying the object of A is costly, the latter should be avoided.

I can't think out any case that the latter is better. So, I just wonder:

Why doesn't the C++ standard prohibit the latter?

C++ - Mixing traditional initializers and member initialization lists - bad idea?

This is partly a style question, partly a correctness question. Submit the following sample (a strip-down of a class which deals with a block of data that contains an embedded header):

class Foo {
 public:
  Foo(size_t size)
      : scratch_(new uint8_t[header_length_ + size]),
        size_(header_length_ + size) {
  }
  ~Foo() {
    delete scratch_;
  }
  Foo(const Foo&) = delete;  // Effective C++
  void operator=(const Foo&) = delete;  // Effective C++
 protected:
  struct Header {
    uint32_t a, b, c, d;
  };
  uint8_t * const scratch_;
  size_t const size_;
  Header * const header_ = reinterpret_cast<Header *>(scratch_);
  static constexpr size_t header_length_ = sizeof(Header);
  static constexpr size_t data_offset_ = header_length_;
  size_t const data_length_ = size_ - data_offset_;
};

First, technical correctness... is it correct that as written, scratch_ and size_ will be initialized first, then header_, then data_length_? (constexpr items are compile-time literal constants and don't figure into initialization order.) Is it also correct that how the initializer is declared, be it traditional int foo = 5 initialization or a member initializer list, has no impact on initialization order, but rather, what matters is solely the order in which members are declared? I found this answer, citing the ISO spec regarding initialization order, and what I gathered is that it's unimportant that scratch_ and size_ appear in the member initialization list versus other members that are given traditional initializers; it only matters that scratch_ and size_ are declared before the other members. Presumably if scratch_ and size_ were declared last, then header_ and data_length_ would (undesirably/incorrectly) be initialized first.

Style question... is it bad style to mix these two initialization styles? My approach is that items in the member initialization list (scratch_, size_) depend on the argument(s) passed into the constructor, while the remaining class members are derived from other class members. Obviously, if an initializer depends on a constructor argument, then it has to go into a member initialization list. Should I throw all initializers into the member initialization list regardless, and abandon traditional initialization? IMO, that may make the code a little harder to follow. Thoughts?

using decltype(*this) to refer to the current class method

I try to compile the following code and receive error:

test.cpp: In member function ‘void CObj::run()’:
test.cpp:19:39: error: ‘th_func’ is not a member of ‘std::remove_reference<CObj&>’
    thread_pool.push_back(std::thread(&std::remove_reference<decltype(*this)>::th_func,this,th_index));
                                       ^

I try to pass the pointer to a class method from another method of the current class and the compiler tells me that th_func is not a member of the given type. How can I fix this code?

#include <iostream>
#include <vector>
#include <thread>

class CObj
{
public:

    void th_func(int i)
    {
        std::cout<<"Hello from thread ("<<i<<")."<<std::endl;
    }

    void run()
    {
        int N_threads=4;
        std::vector<std::thread> thread_pool;
        for(int th_index=0;th_index<N_threads;th_index++)
            thread_pool.push_back(std::thread(&std::remove_reference<decltype(*this)>::th_func,this,th_index));
        // wait for tasks to finish
        for(std::thread& th : thread_pool)
            th.join();

    }
};

int main()
{
    CObj obj;
    obj.run();
}

Ensuring a template class isn't polymorphic?

I was recently working on a C++ library where I was designing a template class that, for efficiency and safety reasons, needed to specifically be non-polymorphic. To ensure that later on I didn't forget this and accidentally break everything, I thought I'd be a good citizen and add a static assertion to that effect.

I initially tried something like this:

template <typename T> class VirtualVerboten {
     ...

     static_assert(!std::is_polymorphic<VirtualVerboten>::value,
                   "This should not be polymorphic."); // Error!
};

This doesn't compile because, at the time that I'm using VirtualVerboten, it's an incomplete type. If this were a non-template class, I'd just put the static_assert right after the type:

class NonTemplateVirtualVerboten {
   ...
}
static_assert(!std::is_polymorphic<NonTemplateVirtualVerboten>::value,
              "This should not be polymorphic.");

But since this is a template class, the analogous idea of making a "template static_assert" isn't legal:

template <typename T> class VirtualVerboten {
     ...

};

template <typename T>              
static_assert(!std::is_polymorphic<VirtualVerboten>::value,
              "This should not be polymorphic."); // Error!

The solution I came up with was to find a member function inside of VirtualVerboten that would likely be used when the template was instantiated (specifically, the constructor), then put the static assertion in there:

template <typename T> class VirtualVerboten {
     VirtualVerboten();
};

template <typename T>
VirtualVerboten<T>::VirtualVerboten() {
  static_assert(!std::is_polymorphic<VirtualVerboten>::value,
                "This should not be polymorphic."); // Yay!
  doSomeActualThingsAtRuntime();
}

This works, except that it relies on the fact that this particular constructor will actually be invoked and therefore instantiated, which fails if there are multiple constructors that could be called.

Is there a "foolproof" way to add this static assertion here? I understand why the original code was producing an error and why you can't have a template static assertion, so this is more of a "did I miss another way of doing this?" rather than a "here's why what you did doesn't work."

C++ priority queue constructor

I found the constructor of priority_queue on http://ift.tt/1fbTFHc is like this : priority_queue (const Compare& comp, const Container& ctnr);, but the example it gives us below is like this: typedef std::priority_queue<int,std::vector<int>,mycomparison> mypq_type;. What's the difference between these two constructors?

I have tried both of them on my own, but the first one didn't work, the priority_queue wasn't sorted from small to large. Here is the code:

priority_queue<greater<int>, vector<int>> pq;
pq.push(4);
pq.push(2);
pq.push(1);
pq.push(3);
pq.push(5);

for (int i = 0; i < 5; i++) {
    cout << pq.top() << endl;
    pq.pop();  
}

The result is still 5, 4, 3, 2, 1

How do I prevent OpenCV from executing __fastfail?

I wanted to try and learn OpenCV (currently using version 2.4.13), so I set up this small program to output an RGB filter from a camera stream. However when I run the program it only runs for about 10 frames, and OpenCV executes this segment of code from invalid_parameter.cpp from the windows SDK:

if (IsProcessorFeaturePresent(PF_FASTFAIL_AVAILABLE))
{
     __fastfail(FAST_FAIL_INVALID_ARG);
}

What is the reason this function is being executed and how do I prevent it from happening again?

main.cpp:

#include <iostream>
#include "Pipeline.h"

int main()
{
    Pipeline *pipeline = new Pipeline();

    VideoCapture feed;
    Mat frame;
    if (!feed.open(0))
        return -1;

    //This for loop runs 7000 times for just for debug purposes
    for (auto i = 0; i < 7000; i++)
    {
        feed >> frame;
        if (frame.empty())
            break;
        cv::waitKey(1);
        pipeline->setsource0(frame);
        try
        {
            pipeline->Process();
        }
        catch (const std::exception& e)
        {
            cerr << e.what();
        }
        Mat* image = pipeline->getrgbThresholdOutput();
        cv::imshow("Output", *image);
    }
    return 0;
}

pipeline.h:

#pragma once
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/features2d.hpp>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <math.h>
using namespace cv;
using namespace std;

class Pipeline {
    private:
        Mat source0;
        Mat rgbThresholdOutput;
        vector<vector<Point> > findContoursOutput;
        void rgbThreshold(Mat &, double [], double [], double [], Mat &);
        void findContours(Mat &, bool , vector<vector<Point> > &);

    public:
        Pipeline();
        void Process();
        void setsource0(Mat &source0);
        Mat* getrgbThresholdOutput();
        vector<vector<Point> >* getfindContoursOutput();
};

pipeline.cpp:

#include "Pipeline.h"

Pipeline::Pipeline() {
}

void Pipeline::Process(){
    //Step RGB_Threshold0:
    //input
    Mat rgbThresholdInput = source0;
    double rgbThresholdRed[] = {100, 240};
    double rgbThresholdGreen[] = {40, 233.53535353535355};
    double rgbThresholdBlue[] = {50, 170};
    rgbThreshold(rgbThresholdInput, rgbThresholdRed, rgbThresholdGreen, rgbThresholdBlue, this->rgbThresholdOutput);
    //Step Find_Contours0:
    //input
    Mat findContoursInput = rgbThresholdOutput;
    bool findContoursExternalOnly = false;
    findContours(findContoursInput, findContoursExternalOnly, this->findContoursOutput);
}

void Pipeline::setsource0(Mat &source0){
    source0.copyTo(this->source0);
}

void Pipeline::rgbThreshold(Mat &input, double red[], double green[], double blue[], Mat &output) {
    cvtColor(input, output, COLOR_BGR2RGB);
    inRange(output, Scalar(red[0], green[0], blue[0]), Scalar(red[1], green[1], blue[1]), output);
}

void Pipeline::findContours(Mat &input, bool externalOnly, vector<vector<Point> > &contours) {
    contours.clear();
    int mode = externalOnly ? CV_RETR_EXTERNAL : CV_RETR_LIST;
    int method = CHAIN_APPROX_SIMPLE;
    cv::findContours(input, contours, mode, method);
}

Mat* Pipeline::getrgbThresholdOutput(){
    return &(this->rgbThresholdOutput);
}

vector<vector<Point> >* Pipeline::getfindContoursOutput(){
    return &(this->findContoursOutput);
}

C++ Sin/Cos calculator

Without focusing on law of Cosine, my code bellow attempts to solve for the given sides and angles. If there is also a way, how can I use cin >> to retrieve multiple characters, as you can see I ask the user to input either 'A' or 'S.'

Here is my code and the results

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
char solvefor;
double A; // I used doubles to have specific answers
double a;
double B;
double b;
double C;
double c;

cout << "What are you trying to solve? <ASA(A) or SSA(S)>";
cin >> solvefor;
if (solvefor == 'S')
{
    cout << "What is the value of b?" << endl;
    cin >> b;
    cout << "What is the angle B?" << endl;
    cin >> B;
    cout << "What is the side c?" << endl;
    cin >> c;
    C = asin((sin(B)/b) * c);                       //I would recieve the answers in radians rahter than degrees, any help?
    cout << "Your missing C angle is " << C << endl;
    A = 180 - C - B;
    cout << "Your missing A angle is " << A << endl;
    a = (sin(A) *b) / sin(B);
} else {
    return 0;       //I will work on law of cosine later
}

}

Template specialisation with enable_if and is_arithmetic for a class

I am trying to implement a Expression class with 2 specialisation for arithmetic types. This is the default class:

    template<typename Left, typename Op, typename Right, typename std::enable_if<!std::is_arithmetic<Left>::value, Left>::type* = nullptr>
class Expression { ... }

And those are the two specialisations:

    template<typename Left, typename Op, typename Right, typename std::enable_if<std::is_arithmetic<Left>::value, Left>::type* = nullptr>
class Expression { ... }

    template<typename Left, typename Op, typename Right, typename std::enable_if<std::is_arithmetic<Right>::value, Right>::type* = nullptr>
class Expression { ... }

If I now compile my code I get this error:

Error C3855 'Expression': template parameter '__formal' is incompatible with the declaration Vector

How can I solve my problem with templates and specialisation or dummy types as I used them.

Placing reference to object on global list or vector

I am looking for a way to place a reference to an object on a global list or vector. I think I need something like weak_from_this() in c++17. Unfortunately I need to use c++11:( I would like to do something like:

typedef std::weak_ptr WP_Test; vector TestVector;

class Test { ... void placeOnVector() { TestVector.push_back(this);} }

But the compiler is unable to convert "this" to a weak_ptr.

Using a class member of type 'array'

I know this is a simple question, but I have not been able to find the answer.

I want a C++ class that manages a large block of memory, where the memory is regularly processed in the GPU when a certain class method is called. The class constructor is passed the size of the array, and after construction the array size never changes. The method that does the parallel_for_each should not waste processor cycles or memory when its not necessary.

How do I do this?

I can't create a concurrency::array as a class member, because I need to know how big the array will be before it is created. I can't have a member that is a pointer to a concurrency::array (and then allocate it with 'new' in, for example, the constructor), because I can't figure out how to specify it to the parallel_for_each.

On a side note, I don't normally need to copy the array between the GPU and host, but its fine if for some reason I have to do that, as long as its not done regularly. Otherwise it would waste processor cycles and memory according to the size of the array.

Here's an example of something like what I want. Of course, the reference/pointer captured by the parallel_for_each is wrong. (This is not checked for syntax):

class MyClass
{
    int* myHostArrayPtr;
    concurrency::array<int,1>* myGpuArrayPtr;

    MyClass(int size)
    {
        myHostArrayPtr = new int(size);

        memset(myHostArrayPtr,0,size * sizeof(int));

        myGpuArrayPtr = new concurrency::array<int,1>(size,myHostArrayPtr);
    }

    void ProcessInGpu()
    {
        parallel_for_each(
            myGpuArrayPtr->extent,
            [&myGpuArrayPtr](index<1> i) restrict(amp)
            {
                myGpuArray[i]+=14;
            }
        );
    }
};

how to use extern function with unknown argumments?

Lets say I have a function drawImage that takes a lot of arguments,some of them are winapi variables like HWND, HDC etc, and i don't want to declare them in my class. but I need to use it in my class.

extern void drawImage();
class A{
       private :
         int n;
        ...
      public :
       ...
       void draw(){
        drawImage(n);
       }
}

the above code gives me the expected error drawImage does not take one argument. so how can I use it?

and I don't want to define my member function in the source file that contains the winapi stuff.

Does std::move() invalidate iterators?

Consider the following program:

struct list_wrapper
{
    std::vector<int>    m_list;
};

int main()
{
    std::vector<int> myList { 1, 1, 2, 3, 5 };

    const std::vector<int>::iterator iter = myList.begin();

    list_wrapper wrappedList;
    wrappedList.m_list = std::move(myList);

    // Can I still dereference iter?

    return 0;
}

After the call to std::move(myList), does iter now point to a valid item inside wrappedList.m_list, or do move constructors invalidate all iterators?

Linux - Catch keyboard events even when on background

I have a LED keyboard and I already have the means to control its colours. But I have troubles to find the means to catch keyboard events in Linux even while my process window is not active (terminal or X-window).

Math method could I use to listen keyboard events even while on background?

Any efficient building function in C++/C to fast uniformly sample b entries without replacement from n entries?

It seems that, using shuffle(Index, Index+n, g) before getting the first b entries is still not efficient when n is very big but b is very small, where Index is a vector/array storing 0 ... (n-1).

Hot to pass a default parameter for std::shared_ptr

This question already has an answer here:

I have a function of type

virtual void foo(bla, bla, bla, std::shared_ptr<LoggerInterface> logger) = 0;

And I want to pass a default parameter with NULL pointer, something like:

virtual void foo(bla, bla, bla, std::shared_ptr<LoggerInterface> logger = NULL) = 0;

So that in implementation, if logger is NULL I do nothing with it, otherwise I use the logger.

I've tried to look for a solution but cannot find..

CUDA C++11, array of lambdas, function by index, not working

I am having trouble trying to make a CUDA program manage an array of lambdas by their index. An example code that reproduces the problem

 #include <cuda.h>
 #include <vector>
 #include <stdio.h>
 #include <stdlib.h>
 #include <time.h>
 #include <sys/time.h>
 #include <cassert>

 #define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
 inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true){
     if (code != cudaSuccess) {
         fprintf(stderr,"GPUassert: %s %s %d\n",
         cudaGetErrorString(code), file, line);
         if (abort) exit(code);
     }   
 }

 template<typename Lambda>
 __global__ void kernel(Lambda f){ 
     int t = blockIdx.x * blockDim.x + threadIdx.x;
     printf("device: thread %i: ", t); 
     printf("f() = %i\n", f() );
 }

 int main(int argc, char **argv){
     // arguments
     if(argc != 2){ 
         fprintf(stderr, "run as ./prog i\nwhere 'i' is function index");
         exit(EXIT_FAILURE);
     }   
     int i = atoi(argv[1]);


     // lambdas
     auto lam0 = [] __host__ __device__ (){ return 333; };
     auto lam1 = [] __host__ __device__ (){ return 777; };


     // make vector of functions
     std::vector<int(*)()> v;
     v.push_back(lam0);
     v.push_back(lam1);


     // host: calling a function by index
     printf("host: f() = %i\n", (*v[i])() );


     // device: calling a function by index
     kernel<<< 1, 1 >>>( v[i] ); // does not work
     //kernel<<< 1, 1 >>>( lam0 ); // does work
     gpuErrchk( cudaPeekAtLastError() );
     gpuErrchk( cudaDeviceSynchronize() );
     return EXIT_SUCCESS;
 }

Compiling with

nvcc -arch sm_60 -std=c++11 --expt-extended-lambda main.cu -o prog

The error I get when running is

➜  cuda-lambda ./prog 0
host: f() = 333
device: GPUassert: invalid program counter main.cu 53

It seems that CUDA cannot manage the int(*)() function pointer form (while host c++ does work properly). On the other hand, each lambda has a different data type, no matter if they are identical. Then, how can we achieve function by index in CUDA?

Accessing second element in map which is object pointer

I'm trying to access second element in my mainRegister map:

 class Manager
{
private:
    std::map<boost::uuids::uuid, Rental*> mainRegister;
    std::vector <Rental*> archiveRegister;
    std::vector<Client*> ClientRegister;
    std::vector<Vehicle*> VehicleRegister;

public:
    Manager();
    void createRental();
    void deleteRental(Rental rent);
    std::string showArchive() const;
    std::string showMain() const;
    std::string showVehicles() const;
    std::string showClients() const;
    void sortDate();
    void sortClient();
    bool checkVehicle(std::map <Vehicle*, Rental*> myMap);
    virtual ~Manager();

protected:

};

Here is what I'm trying to do:

void Manager::deleteRental(Rental* rent)
{
  for (auto it = mainRegister.cbegin(); it != mainRegister.cend()
  {
    if (it.second->getUUID() == rent->getUUID())
    {
      archiveRegister.push_back(it.second);
      mainRegister.erase(it++);
    }
    else
    {
      ++it;
    }
  }
}

My main goal is to find element in map, which second element has the same UUID as the object which is passed to method, and then move that object to archive register vector, and afterwards remove that element from the map.

The errors which I'm getting are :

-struct std::_Rb_tree_const_iterator >' has no member named 'second'|

-no matching function for call to' std::vector::push_back(second_t >)'|

I know that probably the way I'm trying to access the second element of each pair in map is totally wrong, but I don't really know how that could be done .

Std::copy fails in debug build

I have the following code which throws out of bounds exception in debug build but works correctly in release build

std::array<uint, 4> expArray = {51,639,398,744};
unsigned dataArraySize = sizeof(expArray) / sizeof(uint) ;
std::vector<uint> expected ;
std::copy(&expArray[0], &expArray[dataArraySize], back_inserter(expected));

ostream::operator<< is not working with operator-> in shared_ptr

#include<fstream>
#include<string>
#include<memory>
class Log
{
private:
    string errorlog;
    shared_ptr<ofstream> fs;
public:
    Log() :errorlog(""), fs(new ofstream("c:\\Log\\log.txt"), [](ofstream& fs) {fs.close(); })
    {

    }
    void transferLog(string errorlog)
    {
        (*fs)<<(errorlog)    //is working
         fs->operator<<(errorlog);    //not working

    }
}

i know that if it works,it works well in other common situation.

this error list

no instance of overloaded function "std::basic_ofstream<_Elem, _Traits>::operator<< [with _Elem=char, _Traits=std::char_traits]" matches the argument list

Why does gcc hide overloaded functions in the global namespace?

void f() {}

namespace test
{
void f(int) {}    
void g() { f(); } // error in gcc 6.2.0
}

int main()
{
    test::g();
}

Compile it with g++ -std=c++1z main.cpp, the output is as follows:

main.cpp: In function 'void test::g()':
main.cpp:9:4: error: too few arguments to function 'void test::f(int)'
  f(); // error in gcc
    ^
main.cpp:5:6: note: declared here
 void f(int) {}

My compiler is gcc 6.2.0.

Why does gcc hide overloaded functions in the global namespace? Is this conforming to the C++ standard?

Emulate copy-assignment operator for lambdas in C++

This question has two parts

Firstly, can someone explain the rationale behind C++ disabling the copy-assignment operator for lambdas? If you're going to allow the copy constructor, why not the copy-assignment operator?

Secondly, how do you best overcome this limitation without forcing people to write C++03 style functors, or using std::function (the functions I'm dealing with are tiny, and I'd like the compiler to inline them wherever possible)?

Background: I'm trying to implement a flat_map like operation in a stream processing library I'm writing, similar to flatMap in Scala or other functional languages. As a result, I need to create an iterator that iterates over a list of iterators. Each time the flat_map iterator is de-referenced a lambda associated with the inner iterator is executed. The outer iterator needs to switch the inner iterator each time the inner iterator reaches the end. Since the inner iterator contains a lambda, and therefore does not have a copy-assignment operator, it's not possible to switch it. Technically I could solve the problem using dynamic allocation, so that I always call the copy-constructor, but that doesn't seem like the right approach. Here is a snippet of code that might help highlight the problem:

template <typename Iter>
class flat_map_iterator {
public:
  flat_map_iterator& operator++() {
    ++it_inner_;
    if (it_inner_ == (*it_outer_).end()) {
      ++it_outer_;
      // ERROR: cannot be assigned because its copy assignment operator is implicitly deleted
      it_inner_ = (*it_outer_).begin();
    }
    return *this;
  }
private:
  Iter it_outer_; 
  typename Iter::value_type::iterator it_inner_;
};

Returning std::future (or std::shared_future etc) from a method

I am trying to implement a generic RPC invoker to return some sort of a future to the calling service and fail to understand the C++ semantics behind the use of std::future and std::shared_future. So far I have produced the following code, which won't compile because futures cannot be copied, and I cannot figure our how to move further from here. This same concept works perfectly well when implemented with CompletableFuture of netty.io promises in Java.

#include <future>
#include <string>

class Invoker {
    public:
        template<typename RQ, typename RS> std::future<RS> invoke(const RQ& request, RS& inst) const {
            std::promise<RS> promise;
            promise.set_value(inst); // FIXME just for the example
            return promise.get_future();
        }
};

struct GetRateRequest {
        std::string symbol;
};

struct GetRateResponse {
        double rate;
};

class FxRateService {
        const Invoker* invoker;

    public:
        FxRateService(const Invoker* invoker) {
            this->invoker = invoker;
        }

        std::future<double> getRate(std::string symbol) {
            GetRateRequest request = { .symbol = symbol };
            GetRateResponse tmpl = { .rate = 0.0 };
            auto fut = invoker->invoke<GetRateRequest, GetRateResponse>(request, tmpl);

            std::promise<double> res;
            // FIXME: set in async when future is ready
            res.set_value(fut.get().rate);
            return res.get_future();
        }

        double getRateSync(std::string symbol) {
            return getRate(symbol).get();
        }
};

So what am I doing wrong with returning the futures, what should I return instead and how to get the corresponding type conversion?

declare bidirectional matrix using smart pointers in C++

I want to know how to declare a bidirectional array in C++ using smart pointers.. I menage with raw pointers. The code is:

class Matrice{

int size;
int **val;

public:
    Matrice(int size1)
    {
        val = new int* [size1];
        size = size1;
              for (int i = 0; i < size1; i++)
              {
                 val[i] = new int[size1];
              }
              for (int i = 0; i < size1; i++){
                 for (int j = 0; j < size1; j++)
                 {
                    val[i][j] = j;
                 }
              }

    }

    ~Matrice()
    {
        delete []val;
        cout<<"Destroyed matrix! \n";
    }

};

Thanks in advance!

In C++, can two other different shared objects access a Singleton from a third shared object?

I have an application in C++, which loads most of its code from two or more plugins (each with at least one thread). These plugins are '.so' files, it is, share objects. It uses the following code to open the plugins:

pluginHandle = dlopen(fileName, RTLD_NOW|RTLD_GLOBAL);
init_t* init = (init_t*) dlsym(pluginHandle, "init") // Create should return an instance of the class of the plugin
plugin = init();

I arrived to the point to which I need two of those plugins to start adding data to a common Queue. As the application does not allow for communication between both plugins without changing the code in the application itself (a point we are trying to avoid), I think I found a way to solve that:

A dynamic library (shared object), which includes a singleton class with a thread-safe Queue. I would then recompile and link both plugins against the lybrary, and use getInstance() to get the singleton and start adding tasks to the queue.

Is that a safe implementation? Will the singleton Queue work?

Initialize two 2-d array to zero in C/C++

My question is can we initialize 2-d array using int a[10][10] = 0.

According to the top answer in initialize-large-two-dimensional-array-in-c,

int array [ROW][COLUMN] = {0};
which means: "initialize the very first column in the first row to 0, and all other items as if they had static storage duration, ie set them to zero."

However, checking C99 Standard 9899:TC3 and C++11 Standard N4296, I haven't found any official records supporting what was mentioned in this answer.

Besides, I do come across this issue when I try to solve the LeetCode 474. Ones and Zeroes problem with the following solution.

// To make question clear:
// It seems that "int dp[m + 1][n + 1] = 0" cannot initilize all elem to 0
// "memset(dp, 0, sizeof dp)" is necessary to pass the OJ test. Any idea?

class Solution {
 public:
  // m : 0s, n : 1s
  int findMaxForm(vector<string>& strs, int m, int n) {
    int dp[m + 1][n + 1] = 0;
    // We will get "Wrong Answer" without memset() function below
    memset(dp, 0, sizeof dp);
    for (auto& str : strs) {
      auto cost = getCost(str);
      for (int i = 0; i + cost.first <= m; ++i)
        for (int j = 0; j + cost.second <= n; ++j)
          dp[i][j] = std::max(dp[i + cost.first][j + cost.second] + 1,
              dp[i][j]);
    }
    int max = 0;
    for (int i = 0; i <= m; ++i)
      for (int j = 0; j <= n; ++j)
        max = std::max(max, dp[i][j]);
    return max;
  }

 private:
  pair<int, int> getCost(const string& str) const {
    int cnts[] = {0, 0};
    for (char c : str) ++cnts[static_cast<char>(c == '1')];
    return {cnts[0], cnts[1]};
  }
};

Unknown symbol in c++ string throws errors

There is a snippet of code I took from an example and it uses a symbol unknown to me and I can not find anything about it! The snippet is split onto two lines, but if I remove the split in the string, it doesn't throw an error, assumingly because then it becomes part of the "..." string.

cout << "Running 'SELECT 'Hello World!' » AS _message'..." << endl;

However, another usage of the symbol not involved directly in a string throws and error as well:

cout << "(" << __FUNCTION__ << ") on line " » << __LINE__ << endl;

Is this bad syntax for just continuation of a string?

Wrong rapidjson conversion from uint64 to string

I need to output a Uint64 number a = 1185345998335 to file using rapidjson library. I write

writer.Uint64(a);

and debugger says that it's exactly a which is passed into a function. But the output is 4229991935, which is exactly 4 last bytes of the number, and the first 4 bytes are lost.

00000113 fc208dff 1185345998335
00000000 fc208dff 0004229991935

mercredi 28 décembre 2016

Is there an STL comparator for std::set (or std::map) with shared_ptr keys that provides value-based lookups? What exactly does std::owner_less do?

I have a std::map with shared_ptr<T> keys, and I need it to use the actual value (of type T, i.e. *key) for lookups, not the value of the shared pointer itself.

I know I can write my own custom comparator (as I've done below), but I was wondering if the STL supplies a comparator specifically for this purpose.

To demonstrate what I'm talking about, I created this simple example that uses a std::set of strings (I've also put it on GitHub as a gist):

#include <set>
#include <string>
#include <memory>
#include <iostream>
#include <functional>

template< typename T >
struct shared_ptr_comparator {
  bool operator()(const std::shared_ptr<T> &a, const std::shared_ptr<T> &b) const {
    return std::less<T>()(*a, *b);
  }
};

void ptr_set_with_custom_comparator() {
    std::set< std::shared_ptr<std::string>, shared_ptr_comparator<std::string> > ptr_set;

    ptr_set.insert(std::make_shared<std::string>("world"));
    ptr_set.insert(std::make_shared<std::string>("hello"));
    ptr_set.insert(std::make_shared<std::string>("abc"));

    for(auto const& entry : ptr_set) {
        std::cout << *entry << std::endl;
    }
}

void ptr_set_with_owner_less() {
    std::set< std::shared_ptr<std::string>, std::owner_less<std::shared_ptr<std::string>> > ptr_set;

    ptr_set.insert(std::make_shared<std::string>("world"));
    ptr_set.insert(std::make_shared<std::string>("hello"));
    ptr_set.insert(std::make_shared<std::string>("abc"));

    for(auto const& entry : ptr_set) {
        std::cout << *entry << std::endl;
    }
}

void raw_set() {
    std::set<std::string> raw_set;

    raw_set.insert("world");
    raw_set.insert("hello");
    raw_set.insert("abc");

    for(auto const& entry : raw_set) {
        std::cout << entry << std::endl;
    }
}

int main() {
    std::cout << "A basic set of strings:" << std::endl;
    raw_set();
    std::cout << std::endl;

    std::cout << "A set of shared_ptr<string>s with owner_less as the comparator:" << std::endl;
    ptr_set_with_owner_less();
    std::cout << std::endl;

    std::cout << "A set of shared_ptr<string>s with the comparator shared_ptr_comparator:" << std::endl;
    ptr_set_with_custom_comparator();

    return 0;
}

The code above can be complied with clang++ -Wall -std=c++11. Here's the output:

A basic set of strings:
abc
hello
world

A set of shared_ptr<string>s with owner_less as the comparator:
world
hello
abc

A set of shared_ptr<string>s with the comparator shared_ptr_comparator:
abc
hello
world

A sorted ordering when iterating and printing the contents std::set implies that the _actual underlying values) are being compared.

The function raw_set doesn't use shared_ptr, and just uses set<string>, and is simply present for reference.

The function ptr_set_with_custom_comparator works as expected. I am able to achieve what I want with my own shared_ptr_comparator.

However, the output of ptr_set_with_owner_less has left me puzzled. Is owner_less (or owner_before) utilizing the values of the pointers themselves?

Based on all of this, I have two questions:

  • Does anything equivalent to shared_ptr_comparator (defined in the program above), exist in the STL? I ask because the comparator I wrote seems like a really common use case, and I would be very surprised if the STL didn't have anything equivalent to it.

  • What exactly does owner_less and owner_before (which it calls) do? Do they simply check for equivalence of the underlying pointers? I'm not sure if I'm using it right.

Thanks in advance for any answers to this question.

pack expansion with braced-init-list

I decide to implement python's slice with c++ by myself. I wrote a function which accepts variadic slice_info<int> arguments. I compiled with MSVC2015 and it's like the following

template<typename T>
struct slice_info {
    T fr, to, step;
    slice_info(std::initializer_list<T> il) {
    }
    slice_info(const slice_info<T> & x) : fr(x.fr), to(x.to), step(x.step){
    }
};
void slice(slice_info<int>&& s) {
}
template<typename ... Args>
void slice(slice_info<int>&& s, Args&& ... args) {
    slice(std::forward<Args>(args)...);
}
void slice_work_around(const std::vector<slice_info<int>> & vs) {

}
int main(){     
    slice({ 1, 2 }, { 3, 4, 5 }, {7}); // #1 error
    slice({ 1, 2 }, slice_info<int>{ 3, 4, 5 }, slice_info<int>{7}); // #2 yes
    slice_work_around({ {1, 2}, {3, 4, 5}, {7} }); // #3 yes
}

I thought #1 error is because

braced-init-list is not an expression and therefore has no type

I tried #2 and #3 and they worked. However I am still wondering is there are possible ways to make #1 possible. This question is a bit similar with c11-variable-number-of-arguments-same-specific-type, and in my case these variable number of arguments are braced-init-list.

c++ explicit call to constructor and temporary object

#include <iostream>
using namespace std;

class Test
{
    public:
    Test()  { cout << "Constructor i`enter code here`s executed\n"; }
    ~Test() { cout << "Destructor is executed\n";  }
};

int main()
{
     Test();  // Explicit call to constructor

    return 0;
}

in above code we are calling constructor explicitly and When the constructor is called explicitly the compiler creates a nameless temporary object and it is immediately destroyed. why do we need this temporary object??

Is it a bug in MSVC 2010 or I am doing something wrong?

ALL,

Consider following code snippet:

In database_sqlite.h:

class __declspec(dllexport) SQLiteDatabase : public Database
{
    virtual void GetTableProperties(DatabaseTable *table, std::vector<std::wstring> &errorMsg);
protected:
    struct SQLiteImpl;
};

struct SQLiteDatabase::SQLiteImpl
{
    std::wstring m_catalog;
    std::wstring_convert<std::codecvt_utf8<wchar_t> > m_myconv;
};

In database_sqlite.cpp:

void SQLiteDatabase::GetTableProperties(DatabaseTable *table, std::vector<std::wstring> &errorMsg)
{
    sqlite3_stmt *stmt = NULL;
    std::wstring errorMessage;
    int result;
    std::wstring query = L"SELECT * FROM \"sys.abcattbl\" WHERE \"abt_tnam\" = ? AND \"abt_ownr\" = ?;";
    const unsigned char *dataFontName, *headingFontName, *labelFontName;
    int res = sqlite3_prepare_v2( m_db, sqlite_pimpl->m_myconv.to_bytes( query.c_str() ).c_str(), (int) query.length(), &stmt, 0 );
    if( res == SQLITE_OK )
    {
const char *name = sqlite_pimpl->m_myconv.to_bytes( table->GetTableName().c_str() ).c_str();

I'm using MSVC2010 and, to my surprise, "*name" contains empty string. The first call to "to_bytes()" succeeded, since I can check the query that will be used.

Do I have to do something after the first call to "to_bytes()"? Or I simply have to upgrade the compiler?

TIA and Happy Holidays to people on this community.