vendredi 31 mars 2017

How to use vector of vector for reading a graph?

#include <iostream>
#include <vector>
using namespace std;
void addEdge( vector<vector<int> > adj, int, int);
void print_graph(vector<vector<int> > adj);


int main()
{

    vector<vector<int> > adj;
    addEdge(adj,1,2);     // edge from node 1 to node 2
    addEdge(adj,1,3);
    addEdge(adj,1,4);
    addEdge(adj,2,3);
    addEdge(adj,3,4);
    print_graph(adj);
    return 0;
}

void addEdge(vector<vector<int> > adj, int u , int v)
{
    adj[u].push_back(v);

}

void print_graph( vector<vector<int> > adj)
{
    for( int i = 0; i < adj.size() ; i++ )
    {
        for( int j = 0 ; j < adj[i].size(); j++ )
        {
            cout<< adj[i][j];
        }
    }
}

I have written the code for reading the graph and printing it.
Prior to this for reading graph I used to use

vector<int>adj[5]; 

But I have been told that , use

`vector<vector<int> > adj`  or `list<list<int> > adj`  

I tried but I am getting error as

segmentation fault (core dump )

Can anyone help me in using vector of vector ?? Please help for list of list also.

C++ When to use std:: with vectors and other data types?

In looking at some tutorials I have seen people use vectors like std::vector < class > functions, like this:

std::vector< int > organize(std::vector<int> list);

But, in other examples of code, specifically this one, people do this for the parameters:

void printVector(vector<int> a);

I am curious of what the difference between these two is, and in what circumstance I'd use each.

Correctly Writing a Range Based Constructor

I had a question to do with writing a range based constructor for a class but couldn't find the right phrasing to search for help on google.

Suppose I am writing a simple class, like vector, which involves having a range based constructor that inserts elements from the range into the current container:

// foo.h
#ifndef FOO_H
#define FOO_H

#include <iostream>

class Foo {
public:
    Foo() {
        std::cout << "Default constructor called" << std::endl;
    }
    template<class InputIterator> Foo(InputIterator first, InputIterator last) {
        std::cout << "Range based constructor called" << std::endl;
    }

    Foo(size_t n, int val) {
        std::cout << "size_t, int constructor called" << std::endl;
    }

};

#endif // FOO_H

and have a cpp file

#include <iostream>
#include <vector>
#include "foo.h"

using std::cout;    using std::endl;

int main() {
    std::vector<int> v(10, 5);
    Foo f_default;
    Foo f_range(v.begin(), v.end());   
    Foo f_int(314, 159);       // want this to call size_t, int ctctr
    return 0;
}

In the third line in main, we create a Foo f_int(314, 159) which intuitively we want to call the size_t, int constructor. However it is matching the generic template constructor for ranges instead. Is there a way issues like this are addressed in C++? I feel like I am incorrectly dealing with writing range based constructors.

I can imagine you can use template specialization maybe, but don't really see how.

An example where such a situation might happen is if we are writing a vector class where there is a constructor based on a size_t and default value (which would be templatised on the class but I simplified here) and another constructor based on iterator ranges.

Convert float number from nonuniform ranges

So I have this, relatively easy, problem and wondering if the solution for it already exists.

I have to convert a value from one range to another. If there was just one range, like this:

 {-30.0, 30.0} -> {25.0, 50.0}

that would have been easy. But I have a set of ranges:

 {-30.0, -20.0} -> {25.0, 30.0}
 {-20.0,   0.0} -> {30.0, 40.0}
 {  0.0,  30.0} -> {40.0, 50.0}

One solution is to do a linear search on each access. Another solution is to make the ranges to have equivalent length so that the input value could be directly mapped.

Does anyone know a better than linear search solution? Or if a container that performs this kind of conversion already exist?

Thanks so much.

Simple file writing with ostream_iterator creates file, but doesn't write

I have a really simple code to create a text file called "Input.txt", and write to it using ostream_iterator:

using namespace std;


int main()
{
    ofstream os{ "Input.txt" }; 
    ostream_iterator<int> oo{ os,"," };

    vector<int> ints;
    for (int i = 0; i < 1000; i++)
    {
        ints.push_back(i);
    }

    unique_copy(ints.begin(), ints.end(), oo);

    system("PAUSE");
    return 0;
}

The code above creates a "Input.txt", but there is nothing written to it. Am I missing something really obvious and fundamental?

Custom "nullptr", but how to understand the codes?

It's from Wikipedia, if our compiler don't support c++11 , we can implement one by ourselves , just like below:

const class nullptr_t
{
public:
    template<class T>
    inline operator T*() const
        { return 0; }

    template<class C, class T>
    inline operator T C::*() const
        { return 0; }

private:
    void operator&() const;
} nullptr = {};

I can't understand the above codes.

Is assigning const reference is actually faster than move semantics?

Consider following C++ code:

using DataType = std::vector<int>;
class Foo
{
private: 
    DataType m_data;
public:
    void setConstLvalue (const DataType& data) 
    { 
        m_data = data; 
    }
    void setRvalueMove  (DataType&& data)      
    {
        m_data = std::move(data); 
    }
};

I thought setRvalueMove one would be faster, of course. And yes, I was right.

But it was only faster if I pass r-value vector<int> to both methods. This time, I explicitly declared another vector<int> and pass through both methods(l-value), setConstLvalue was about 3 times faster, optimized or not.

Live Demo

My questions

  1. Why is setConstLvalue is faster than setRvalueMove, if I pass l-value through them?
  2. And why not if I pass r-value?
  3. Is time complexity of vector move-assignment is constant, or linear in size?

Strange strings behaviour when const reference

I encountered a strange behaviour with const reference strings when it goes over 15 characters. It simply replaces the beginning of the string by null bytes.

Class A
{
public:
  A(const std::string& str) : str_(str)
  {
    std::cout << str_ << std::endl;
  }
  void test()
  {
    std::cout << str_ << std::endl;
  }
private:
  const std::string& str;
};

int main()
{
  //printing the full string "01234567890123456789"
  A a("01234567890123456789");
  //replacing first bytes by '\0', printing "890123456789"
  a.test();
}

This is happening only with strings exceeding 15 characters. If a remove the const & in the attribute of the class, I don't have this problem anymore I've experienced in an other project memory leaks in my code when strings were exceeding 15 characters, so I wonder :

What is really happening when a string goes over 15 characters ?

Function not writing to txt file

I have a program that uses various structs and functions to read information into a struct from an output file, do something with it, and write to an output file if a condition is met. Everything is working properly, except the function that's supposed to write to the output file isn't doing so. I'm required to have a function that writes to the output file, so doing it in main isn't an option. Here's my code:

#include <iostream>
#include <iomanip>
#include <fstream>
#include <climits>

using namespace std;

struct subscriberName{
    string firstName;
    string lastName;
    int custId;
};

struct address{
    string street;
    string city;
    string state;
    int zip_code;
};

struct date{
    string month;
    int day;
    int year;
};

struct renewal_information{
    int monthsLeft;
    date lastNoticeSent;
};

struct subscriber{
    subscriberName custName;
    address custAddress;
    renewal_information custInfo;
};

void openInFile(ifstream&);
void openOutFile(ofstream&);
subscriber recordIn(ifstream&, subscriber&, address&, date&, int&,     int&);
void expired(subscriber&, ofstream&);

int main() {
    ifstream inFile;
    ofstream outFile;
    openInFile(inFile);
    openOutFile(outFile);
    subscriber customer;
    address custAddress;
    date custDate;
    int currentLine=0, numProcessed=0, numExpired=0;

    while (!inFile.eof()){
        recordIn(inFile, customer, custAddress, custDate, currentLine,     numProcessed);

        if (customer.custInfo.monthsLeft==0) {
            expired(customer, outFile);
            numExpired++;
        }
    }
    cout<<endl<<string(47, '-')<<endl<<"Number of subscribers     processed: "<<numProcessed
        <<endl<<"The number of expired subscriptions is: "    <<numExpired<<endl
        <<string(47, '-')<<endl<<endl;

    inFile.close();
    outFile.close();
    return 0;
}

void openInFile(ifstream& inFile){
    string inFileName;
    do{
        cout<<"Enter input file name: ";
        cin>>inFileName;
        cout<<inFileName<<endl;
        inFile.open(inFileName.c_str());
    }
    while (!inFile);
    if (inFile.fail()){
        cout<<"input file failed to open\n";
        inFile.clear();
    } else
        cout<<inFileName<<" opened successfully\n";
}

void openOutFile(ofstream&){
    string outFileName;
    ofstream outFile;
    do{
        cout<<"Enter output file name: ";
        cin>>outFileName;
        cout<<outFileName<<endl;
        outFile.open(outFileName.c_str());
    }
    while (!outFile);
    if (outFile.fail()){
        cout<<"output file failed to open\n";
        outFile.clear();
    } else
        cout<<outFileName<<" opened successfully\n";
}

subscriber recordIn(ifstream& inFile, subscriber& customer, address&     custAddress, date& custDate, int& currentLine, int& numProcessed){
    inFile.ignore(currentLine, '\n');

    getline(inFile, customer.custName.firstName, '\n');

    if (inFile.eof()){
        return customer;
    }
    else {
        getline(inFile, customer.custName.lastName, '\n');
        inFile >> customer.custName.custId;
        cout << "==> Processing Customer ID: " <<     customer.custName.custId << endl;
        numProcessed++;

        inFile.ignore(INT_MAX, '\n');
        getline(inFile, customer.custAddress.street, '\n');
        getline(inFile, customer.custAddress.city, '\n');
        getline(inFile, customer.custAddress.state, '\n');
        inFile >> customer.custAddress.zip_code;
        inFile >> customer.custInfo.monthsLeft;
        inFile >> customer.custInfo.lastNoticeSent.month;
        inFile >> customer.custInfo.lastNoticeSent.day;
        inFile >> customer.custInfo.lastNoticeSent.year;

        currentLine = currentLine + 11;
    }
    return customer;
}

void expired(subscriber& customer, ofstream& outFile){
    while (customer.custInfo.monthsLeft==0) {
        outFile << customer.custName.firstName;
        outFile << customer.custName.lastName;
        outFile << customer.custName.custId;
        outFile << customer.custAddress.street;
        outFile << customer.custAddress.city;
        outFile << customer.custAddress.state;
        outFile << customer.custAddress.zip_code;
        outFile << customer.custInfo.monthsLeft;
        outFile << customer.custInfo.lastNoticeSent.month;
        outFile << customer.custInfo.lastNoticeSent.day;
        outFile << customer.custInfo.lastNoticeSent.year;
        customer.custInfo.monthsLeft=-1;
        outFile.flush();
    }
}

Why does the ternary operator work differently at compile time compared to the run time?

template <uint_fast64_t MAX_RAND>
    struct RandomLimit
    {
        static const uint_fast64_t steps =
            RAND_MAX >= MAX_RAND ? 
            1 : 
            RandomLimit<MAX_RAND / (RAND_MAX + 1)>::steps + 1;
    };

The code above yields and error; steps is undefined. At run time, if a function call would be in place of the last expression, this function would not be called and no side - effects would happen. Why isn't this code eliminated when the condition holds true?

Note that RAND_MAX is the cstdlib constant and I'm using a Visual Studio 2015 setup.

How to avoid deadlock when the called method uses the same lock that the caller already locked?

How to avoid deadlock when the called method uses the same lock that the caller already locked?

I have and method called closeUnusedConnections(), that creates a std::unique_lock but its caller already created a std::unique_lock with the same std::mutex: Foo::m_myMutex.

Do I have to release the lock before calling the subroutine?

Obs.: I can't integrate both methods because the closeUnusedConnections is also called independently.

Some code:

void Foo::closeUnusedConnections()
{   
   std::unique_lock< std::mutex > lock( m_mtx );
   // do stuff
}

Foo::CommNodePtr Foo::getConnection()
{   
   std::unique_lock< std::mutex > lock( m_mtx );
   // do stuff
   if( true /*some condition*/ )
   {
      lock.unlock();     // The goal is to avoid this unlock
                         // someone could get the lock between
                         // this unlock until closeUnusedConnections's lock.
      closeUnusedConnections(); 
   }
   // etc
}

Why this constructor is called twice?

I have this code:

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

class Hello{
    public:
    Hello(){std::cout<<"Hello world!"<<std::endl;}
};

class Base{
    public:
    Base(const Hello &hello){ this->hello = hello;}
    private:
    Hello hello;
};

class Derived : public Base{
    public:
    Derived(const Hello &hello) : Base(hello) {}
};

int main()
{
    Hello hello;
    Derived d(hello);
    return 0;
}

The resulting print is:

Hello world!
Hello world!

Why this happens?

Mixing String and Numeric Input in c++

I came across this program listing in c++primer plus

// numstr.cpp -- following number input with line input
#include <iostream>
int main()
{
using namespace std;
cout << "What year was your house built?\n";
int year;
cin >> year;
cout << "What is its street address?\n";
char address[80];
cin.getline(address, 80);
cout << "Year built: " << year << endl;
cout << "Address: " << address << endl;
cout << "Done!\n";
return 0;
}

Due to the carriage return after first cin the cin.getline doesn't work but when I replace cin.getline with cin>>address; the address is input why is it happening ? Please also tell how the input and output buffer work with cin and cout. Thanks

Overload custom comparator to std::map

I am trying to solve this problem. I came up with this solution:

typedef unordered_map<string, double> stockDictType;

class StockTicker {
  class Comparator {
  public:
    inline bool operator() (const string &a, const string &b) const {
      return stocksDict.at(a) < stocksDict.at(b);
    }
  };

  stockDictType stocksDict;

  map<string, stockDictType::iterator, Comparator> stocksTicker; // this is where I need a custom comparator method

  int tickerSize;

public:
  StockTicker(int k): tickerSize(k) {}

  // some other methods
};

As is evident, this fails to compile: StockTicker::stocksDict is not a static member. Now I can't make it so because I could require multiple instances of the StockTicker class.

std::map uses a strict comparator function parameter definition (std::map will only pass in the keys to be compared), so I can't overload it to pass a reference to the current instance of the StockTicker class (which I could've used to get access to StockTicker::stocksDict through public getters)

I took inspiration from this SO question and the subsequent answer to do this:

typedef unordered_map<string, double> stockDictType;

class StockTicker {
  class Comparator {
  public:
    stockDictType &_stockDictRef;

    explicit Comparator(stockDictType &stocksDict): _stockDictRef(stocksDict) {}

    inline bool operator() (const string &a, const string &b) const {
      return _stockDictRef.at(a) < _stockDictRef.at(b);
    }
  };

  stockDictType stocksDict;
  map<string, stockDictType::iterator, Comparator> stocksTicker(Comparator{stocksDict});
  int tickerSize;

public:
  StockTicker(int k): tickerSize(k) {}

  void addOrUpdate(string name, double price) {
    stocksDict[name] = price;
    stocksTicker.at(name) = stocksDict.find(name);
  }

  vector<stockDictType::iterator> top() {
    vector<stockDictType::iterator> ret(tickerSize);

    auto it = stocksTicker.begin();
    for(int i = 0; i < tickerSize; i++, it++)
      ret[i] = it->second;

    return ret;
  }
};

This won't compile either. I get this kind of error in the StockTicker::addOrUpdate() and StockTicker::top() methods: error: '((StockTicker*)this)->StockTicker::stocksTicker' does not have class type.

I tried a bunch of other stuff too (like declaring a public comparator method in the StockTicker class itself and trying to pass a function pointer of it to std::map. That failed as well; StockTicker::stocksTicker gets declared before the comparator method does and the compiler complains).

Any ideas on how to go about fixing this?

Why C++ std::move does not work on std::initializer_list ? Rvalue

In the funtions bellow, doA is overrided to accept const& and && of std::string, doA_ is overrided to accept these two types of std::initializer_list. But what seems to be wrong is that, in the fisrt doA_ function, a std::move does not correctly cast 'std::string' to 'std::string&&', so there the second doA called,not the first one. Even if I use 'doA(static_case(*it))' instead,it is the same result.However , if I use 'doA("a string")',then the first doA called. Why is that?Why do they behave differently?

#include <string>
#include <iostream>

void doA(std::string &&s)
{
        std::cout << "doA && "<<std::endl;
}

void doA(const std::string &s)
{
        std::cout << "doA const & "<<std::endl;
}
void doA_(initializer_list<std::string> &&l)
{
        std::cout << "doA_ &&"<<std::endl;
        auto it=std::begin(l);
        doA(std::move(*it));//print 'doA const &',but it is expected to be 'doA &&'
        //doA(static_cast<const std::string &&>(*it));  //same with above
        //doA("a string");   //print 'doA &&'
              //======Doesn't work as expected

}
void doA_(const initializer_list<std::string> &l)
{
        std::cout << "doA_ const &"<<std::endl;
        auto it=std::begin(l);
        doA(*it);
}


int main()
{
        initializer_list<std::string> l={"a","b"};
        doA_(l);//doA_ const &
        doA_(std::move(l));//doA_ &&
        doA_({"c","d"});//doA_ &&
        return 0;
}

//=========output
    doA_ const &
    doA const &
    doA_ &&
    doA const &
    doA_ &&
    doA const &

What does const means in auto return declaration with trailing return type?

I need to return a const reference from the function. This code does the thing:

auto test()->add_lvalue_reference<const int>::type
{
    static int i{50};
    return i;
}

int & i{test()}; // doesn't compile

But this snippet, that looks painfully similar, gives an incorrect result:

auto const test()->add_lvalue_reference<int>::type
{
    static int i{50};
    return i;
}

int & i{test()}; // compiles thougth test() returned a const

I moved keyword const from the type declaration to the return declaration.

At first, I thought, that after deduction the function signature became in the second case:

int & const test(); // not valid - const qualifiers cannot be applied to int&

This is not a valid c++. But with auto specifier it compiles.

So my question is what does const means in function return type with auto trailing return? Or maybe it's discarded?

Copy constructor called instead of Operator= [duplicate]

I’m trying to do a simple exercise now with a Matrix and I want to implement this operations: Matrix a, Matrix b, Matrix c(a), Matrix d = a, Matrix e = a + b. For the moment I keep it simple but later I want to do the same thing, but with dynamic allocation and later with smart pointers.

I declared an explicit copy constructor and I overloaded operator=, I also declared a destructor so I have the rule of three.

Here are my functions:

Matrix& Matrix::operator=(const Matrix& opEven)
{
    std::cout << "Operator = " << std::endl;
    for (int i = 0; i < ORD; i++)
    {
        for (int j = 0; j < ORD; j++)
        {
            arr1[i][j] = opEven.arr1[i][j];
        }
    }

    return *this;
}

Matrix::Matrix(const Matrix& obj) 
{
    std::cout << "Constructing matrix using copy c-tor." << std::endl;
    for (int i = 0; i < ORD; i++)
    {
        for (int j = 0; j < ORD; j++)
        {
            arr1[i][j] = obj.arr1[i][j];
        }
    }
}

The problem is that, when I try to use Matrix d = a my compiler use the copy constructor, not my operator=.

Output:

Solution with map gave AC and Solution with unordered_map gave WA. why?

I am looking for any difference between map and unordere_map which is now known by most of people.

The problem : Problem Link

the solution with map: Accepted Solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    int N;
    cin >> N;
    map<int,int> mp;
    map<int,int> ::iterator it;
    int ans = 0;
    for(int i=0;i<N;i++){
        int X;
        cin >> X;
        mp[X]++;
    }    
    for(it=mp.begin();it!=mp.end();++it){
        int X = it->first;   
        //cout<<it->first<<" "<<it->second<<endl;
        ans = max(ans,mp[(X-1)]+mp[(X)]);
    }
    cout<<ans<<endl; 
    return 0;
}

the solution with unordered_map: WA Solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    int N;
    cin >> N;
    unordered_map<int,int> mp;
    unordered_map<int,int> ::iterator it;
    int ans = 0;
    for(int i=0;i<N;i++){
        int X;
        cin >> X;
        mp[X]++;
    }     
    for(it=mp.begin();it!=mp.end();++it){
        int X = it->first;   
        //cout<<it->first<<" "<<it->second<<endl;
        ans = max(ans,mp[(X-1)]+mp[(X)]);
    }
    cout<<ans<<endl; 
    return 0;
}

As far as I know that only difference with map and unordered_map is that map contain key in sorted fashion while unordered_map not.

Invoking ranges::for_each with lambda and global function

The following code works as expected:

void foo(auto const &){}

auto const rng{ranges::view::all(v)};
ranges::for_each(rng, [](auto const & r){
    foo(r);
});

But the following:

void foo(auto const &){}

auto const rng{ranges::view::all(v)};
ranges::for_each(rng, &foo);

Gives the compilation error:

template argument deduction/substitution failed:
couldn't deduce template parameter 'F'

I took a look at the source but to be honest I couldn't understand the problem.

Does Flow or TypeScript have a way to use the return type of a function as a separate type

C++ has the decltype keyword that allows getting the return type of a function without evaluating it, and I was wondering if the typed dialects of JS had something similar. I would imagine it working somewhat like this:

let foo = () => 'bar'
let baz: typeof foo() // uses the inferred return type of foo()

How to convert an Int32 array pointer to an Int8_t array pointer?

Any idea. I tried this:

int *p = (int*)malloc(N*sizeof(int));
...//set the value of p
int8_t *q = reinterpret_cast<int8_t *>(p);

But it doesn't work.

Compatibility issues between typedefs

I am using BOOST_STRONG_TYPEDEF to prevent misuses of different string-based ID types. I am however running into compatibility problems between the original type and its typedef.

I have an std::string which contains a list of IDs, separated by commas. I need to store them into a set. The code would look like:

#include <boost/algorithm/string/split.hpp>
#include <boost/serialization/strong_typedef.hpp>
#include <boost/algorithm/string/classification.hpp>

#include <set>
#include <vector>

BOOST_STRONG_TYPEDEF(std::string, MY_ID)

int main()
{
    std::string line("ID1,ID2,ID3");

    // Use boost::split to get all the strings into a vector
    std::vector<std::string> id_vec;
    boost::split(id_vec, line, boost::is_any_of(","));

    // Generate a set of MY_ID. Do not use range constructor since the compiler
    // error is clearer this way
    std::set<MY_ID> ids;
    for (auto const & id : id_vec)
    {
        ids.insert(id);
    }
}

This doesn't compile, since std::string cannot be inserted into a std::set<MY_ID>. However, if I declared the vector to be of type std::vector<MY_ID> it would not work with boost::split.

I have found a work around by adding a temporal variable when inserting:

for (auto const & id : id_vec)
{
    MY_ID tmp(id);
    ids.insert(tmp);
}

This works but seems hacky. Is there a more concise way?

jeudi 30 mars 2017

Debugging array related error ( Assertion `(old_top == initial_top (av) && old_size == 0)) || [...]

I was working to implement the rod cutting problem and I encountered this error:

a.out: malloc.c:2392: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted (core dumped)

The dashed comment block is where I suspect the error is coming from, but I'm not sure why. Trying to run under gdb I am having hard time pin-pointing it (seems to be crashing at i = 7) (compiling using: g++)

#include <iostream>
#include <cstdlib>

using namespace std;

int max_from(int * arr, int n)
{
    int maxval = arr[1];
    for(size_t i = 2; i < n; ++i)
        if(arr[i] > maxval) maxval = arr[i];

    return maxval;
}

int main()
{
    int n = 11;

    int * V = new int[n]; // given arr, price at(i)
    int * C = new int[n]; // optimal at length(i)

    V[0] = 0; // non-affecting value, using 1 as starting point

    V[1] = 1;
    V[2] = 5;
    V[3] = 8;
    V[4] = 9;
    V[5] = 10;
    V[6] = 17;
    V[7] = 17;
    V[8] = 20;
    V[9] = 24;
    V[10] = 30;

    C[0] = 0;

    // --------------------------------------------------

    for(size_t i = 1; i < n; ++i)
    {
        int * arr = new int[i];
        for(size_t k = 1; k <= i; ++k)
        {
            arr[k] = V[k] + C[i-k];
        }

        C[i] = max_from(arr, n);

        delete [ ] arr;
    }

    cout << max_from(C, n) << '\n'; // maximized cost
    // --------------------------------------------------

    delete [ ] V;
    delete [ ] C;
}

Virtual method with variadic arguments

I am trying to implement a logging system abstracted behind a locator service (in the style of this guide) in such a way that the logging system can be subclassed for various different logging situations. I would prefer to be able to use printf style format strings instead of <<, but that means supporting variable number of arguments. Variadic templates can easily solve this, however, they cannot be virtual, which means that the base logging class cannot be abstract (as an interface).

Ideally what I'd need is some way to have the parent method not templated but just accepting of a parameter pack which it would forward to the right (templated) child method. I've mostly seen two ways of doing this, one which is using va_list which apparently is unsafe, complicated and not really meant to interact with variadic templates easily, and CRTP, which would work but means that no pointer can be declared of the abstract base class in the locator object without knowing the subclass type, which defeats the purpose.

Here is example code assuming that virtual templates were a thing:

class Logger
{
    public:
        template <typename ... Args>
        virtual void print(char *filename, int line, std::string &&msg, Args&& ... args) = 0;

    protected:
        template <typename ... Args>
        std::string format(char *filename, int line, std::string &msg, Args&& ... args)
        {
            std::string output = "%s at line %i: " + msg;
            int size = std::snprintf(nullptr, 0, output.c_str());
            // +1 for null termination
            std::vector<char> buf(size + 1);
            std::snprintf(&buf[0], buf.size(), output.c_str(), filename, line, args...);
            return std::string(&buf[0]);
        }


};

class PrintLogger : public Logger
{
    public:
        template <typename ... Args>
        void print(char *filename, int line, std::string &&msg, Args&& ... args)
        {
            std::cout << format(filename, line, msg, args...);
        }
};

Here is example code with the CRTP solution (which breaks the locator):

template <typename Loggertype>
class Logger
{
    public:
        template <typename ... Args>
        void print(char *filename, int line, std::string &&msg, Args&& ... args)
        {
            Loggertype::print(filename, line, msg, args...);
        }

    protected:
        template <typename ... Args>
        std::string format(char *filename, int line, std::string &msg, Args&& ... args)
        {
            std::string output = "%s at line %i: " + msg;
            int size = std::snprintf(nullptr, 0, output.c_str());
            // +1 for null termination
            std::vector<char> buf(size + 1);
            std::snprintf(&buf[0], buf.size(), output.c_str(), filename, line, args...);
            return std::string(&buf[0]);
        }


};

class PrintLogger : public Logger<PrintLogger>
{
    public:
        template <typename ... Args>
        void print(char *filename, int line, std::string &&msg, Args&& ... args)
        {
            std::cout << format(filename, line, msg, args...);
        }
};

And here is the locator:

class Global {
    public:
        static void initialize() { logger = nullptr; }
        static Logger& logging()
        {
            if (logger == nullptr)
            {
                throw new std::runtime_error("Attempt to log something before a logging instance was created!");
            }
            return *logger;
        }
        static void provide_logging(Logger *new_logger) { logger = new_logger; }
    private:
        static Logger *logger;
};

array, std::list, std::vector inserting time

I am making a test program to measure time for storage of each container. The following is my code for the test.

#include <list>
#include <vector>
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;

void insert(list<short>& l, const short& value);
void insert(vector<short>& v, const short& value);
void insert(short arr[], int& logicalSize, const int& physicalSize, const short& value);

int main() {
    clock_t start, end;
    srand(time(nullptr));

    const int SIZE = 50000;
    const short RANGE = 10000;
    list<short> l;
    vector<short> v;
    short* arr = new short[SIZE];
    int logicalSize = 0;

    // array
    start = clock();
    cout << "Array storage time test...";
    for (int i = 0; i < SIZE; i++) {
        try {
            insert(arr, logicalSize, SIZE, (short)(rand() % (2 * RANGE + 1) - RANGE));
        } catch (string s) {
            cout << s << endl;
            system("pause");
            exit(-1);
        }
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    // list
    cout << "List storage time test...";
    start = clock();
    for (int i = 0; i < SIZE; i++) {
        insert(l, (short)(rand() % (2 * RANGE + 1) - RANGE));
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    // vector
    cout << "Vector storage time test...";
    start = clock();
    for (int i = 0; i < SIZE; i++) {
        insert(v, (short)(rand() % (2 * RANGE + 1) - RANGE));
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;



    delete[] arr;
    system("pause");
    return 0;
}

void insert(list<short>& l, const short& value) {
    for (auto it = l.begin(); it != l.end(); it++) {
        if (value < *it) {
            l.insert(it, value);
            return;
        }
    }
    l.push_back(value);
}

void insert(vector<short>& v, const short& value) {
    for (auto it = v.begin(); it != v.end(); it++) {
        if (value < *it) {
            v.insert(it, value);
            return;
        }
    }
    v.push_back(value);
}

void insert(short arr[], int& logicalSize, const int& physicalSize, const short& value) {
    if (logicalSize == physicalSize) throw string("No spaces in array.");
    for (int i = 0; i < logicalSize; i++) {
        if (value < arr[i]) {
            for (int j = logicalSize - 1; j >= i; j--) {
                arr[j + 1] = arr[j];
            }
            arr[i] = value;
            logicalSize++;
            return;
        }
    }
    arr[logicalSize] = value;
    logicalSize++;
}

However, when I execute the code, the result seems a little different from the theory. The list should be fastest, but the result said that insertion in the list is slowest. Can you tell me why?

Very very basic C++ class to represent JSON? [on hold]

I searched a lot but cannot find a very basic C++ class to represent JSON. Like something that can be done within an hour. I have seen this, which has list of many C++ - JSON libraries.

List of many JSON libraries in C++

I'm not looking for something which can handle each and every case. I'm looking for something simple and just complete design(Without implementation is fine) so that I can get an idea of how would I store string, array, int, double, object. Most efficient way. I don't want to use BOOST but C++11 is fine.

Consider this question is being asked for an on-site interview. I just need to design it in an hour and show how would I access and/or insert.

Convert object function to function pointer

I'm trying convert a object function to function pointer but can't get it, i've done something like this, simple example:

typedef struct
{
    int v1;

    int DoSome(int a)
    {
        return v1 * a;
    }
} strx;


int main()
{
    strx a; // instance...
    a.v1 = 2;


    std::function<int(strx* instance, int value)> DoSome = std::mem_fn(&strx::DoSome);

    cout << DoSome(&a, 4) << endl; // 16 ok 

    int(*pDoSome)(strx* instance, int value) = (int(*)(strx*, int))std::mem_fn(&strx::DoSome); // syntax error

    // ptr method...
    pDoSome(&a ,4);

    return 0;
} 

and i have obtained something like:

main.cpp [Error] invalid cast from type 'std::_Mem_fn' to type 'int ()(strx, int)'

How i can do correctly the casting?

What is the simplest way in C++ to get and continue to call a class method, the type of which the current class does not know?

Example: Suppose we are developing a simple graphical interface:

We have windows and controls. What do we want:

  • There is a base window class that implements the GUI functionality hidden from the user.
  • From the base window, the user inherits a specific window.
  • There is a class of a button, an instance of which the user can add to his window.
  • The user can transfer the method of his window, and he will be executed when clicking this button.

I'm interested in how to reach the last point.

Kind of pseudo-code:

class BaseWindow;

class Button
{
public:
            Button(BaseWindow* parent)
            {
                        parent->AddButton(this);
            }

            void SetBehavior(/*Owners pointer and owner's methos*/)
            {
                        /* Save Owner pointer and owner's method*/
            }

            void Clicked(/*coords*/)
            {
                        if(/*coords == my coords*/)
                        {
                                    /*Call Owner's method*/
                        }
            }
};

class BaseWindow
{
            vector<Button*> Buttons;

            WindowClicked(/*coords*/)
            {
                    for(auto i:Buttons)
                    {
                                i->Clicked(/*coords*/);
                    }
            }

public:
            void AddButton(Button* butt)
            {
                            Buttons<<butt;
            }

};

class UserWindow:public BaseWindow
{
            Button MyButton;
public:
            void FunctionForButton(Button* butt){ cout<<"Say Hello, my sweet button";}

            UserWindow():MyButton(this)
            {
                        MyButton.SetBehavior(/*Put here my Function for Button and my pointer*/);
            }
};

C++ : How to read properties of a executable file?

I want to read the file properties like File Description , Product name , Copyright of a exe file. Is there any Windows API for it?

function type with ternary operator

I try this code:

    int a=1;
    std::function<int (int, int)> getM = a?
    [](int x, int y) {
        return (x+y);
    } :
    [](int x, int y) {
        return (x*y);
    };


    cout<<getM(1,2);

In visual studio it gives an error: error C2446: ':' : no conversion from 'wmain::' to 'wmain::' 1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

In GCC it's compiled. I suppose that GCC is the correct behaviour, but I'm not sure. What are other options to make this on VS2013?

Iterator referencing to nothing on 8th element PLF::Colony

I am having an interesting issue. For starters, I am currently developing a 2D geometry editor where the user is able to draw lines and arcs. In order to draw a line and arc, the user needs to select 2 nodes.

In an earlier question on the forum, I was wondering if there was anything available that will not invalidate pointers when elements are erased (or inserted) but is not an std::list (for various reasons that are scattered throughout stack overflow). A user recommended that I take a look at the plf::colony class. Which, in short, acts like std::list but has the speed of std::deque in many instances.

Anyways, I am implementing this class in my program to contain the nodes, lines, and arcs. I was able to successfully integrate the class and everything builds. However, I notice that there is a bug in my bug when I go to delete nodes.

I have narrowed down the issue to be this: If I create less then 10 nodes, my code is able to delete all of the nodes without an issue. However, if I select all of the 10 nodes, my program crashes. If I draw 20 nodes and select 10 of them for deletion, my program crashes. If I draw 15 nodes and select 5 of them, everything is good. If I draw 15 nodes and select 7 of them, everything is fine. If I draw 15 nodes and select 8, the program crashes. If I draw 50 nodes and select 8 for deletion, the program crashes. There is something about the 8th node that appears to crash the program.

Later, I stepped through the code (that I have posted below) and everything is fine until the iterator reaches the 8th item. There, the iterator points to nothing and crashes the program. The program crashes when it tries to erase the iterator from the colony.

I was wondering if anyone else using plf::colony ran into the same issue and what they did to fix the bug? Or is there something wrong with the way that I am setting up my code?

  if(_editor.getNodeList()->size() > 1 && _nodesAreSelected)
    {
        plf::colony<node>::iterator stopIterator = _editor.getNodeList()->end();
        for(plf::colony<node>::iterator nodeIterator = _editor.getNodeList()->begin(); nodeIterator != _editor.getNodeList()->end(); ++nodeIterator)
        {
            if(nodeIterator->getIsSelectedState())
            {
                if(_editor.getLineList()->size() > 1)
                {
                    /* Need to cycle through the entire line list and arc list in order to determine which arc/line the node is associated with and delete that arc/line by selecting i.
                     * The deletion of the arc/line occurs later in the code*/

                    for(plf::colony<edgeLineShape>::iterator lineIterator = _editor.getLineList()->begin(); lineIterator != _editor.getLineList()->end(); ++lineIterator)
                    {
                        if(*lineIterator->getFirstNode() == *nodeIterator || *lineIterator->getSecondNode() == *nodeIterator)
                        {
                            lineIterator->setSelectState(true);
                        }
                    }
                }


                if(_editor.getArcList()->size() > 0)
                {
                    for(plf::colony<arcShape>::iterator arcIterator = _editor.getArcList()->begin(); arcIterator != _editor.getArcList()->end(); ++arcIterator)
                    {
                        if(*arcIterator->getFirstNode() == *nodeIterator || *arcIterator->getSecondNode() == *nodeIterator)
                        {
                            arcIterator->setSelectState(true);
                        }
                    }
                }

                int size = _editor.getNodeList()->size();

                if(_editor.getNodeList()->size() <= 1 && _editor.getNodeList()->begin()->getIsSelectedState())
                {
                    if(_editor.getNodeList()->size() == 1)
                        _editor.getNodeList()->clear();
                    break; 
                }

               _editor.getNodeList()->erase(nodeIterator);
            }
        }
    }
    else if(_editor.getNodeList()->size() == 1 && _editor.getNodeList()->begin()->getIsSelectedState())
    {
        _editor.getNodeList()->clear();
    }

find_if with vector

I realize that similar questions has been asked before but i didn't find the answer to my question so I'm just gonna post it here.

iteratorHelper takes an accountNr as argument, searches a vector of unique_ptrs and returns a bool. The problems is in the second method.

The if-statement in getAccInfo(size_t pAccNr) is giving me problems. My IDE is complaining about the "iteratorHelper" saying that "The object has type qualifiers that are not compatible with the member function "Client::iteratorHelper". Object type is const Client" I'm not entirely sure what I'm missing here so if anyone could point me in the right direction?

    auto Client::iteratorHelper(size_t accountNr )    {
                return find_if(accounts.begin(), accounts.end(),
                    [&accountNr ](const unique_ptr<Account>& account)
                {return account->getAccountNr() == accountNr ; });

    unique_ptr<Account> const & Client::getAccInfo(size_t pAccNr) const    {
                if (iteratorHelper(pAccNr) != accounts.end())
                {
                    auto const& index = distance(accounts.begin(), iteratorHelper(pAccNr));
                    return accounts[index];
                }
                return nullptr;    
                }

Cmake did not use C++11 flag using CXX_STANDARD?

I'm fairly new to cmake and I'm trying to use the mongodb driver for C++ by using this tutorial: http://ift.tt/2oCnr38. The tutorial says you need C++11, so I tried the recommended way which is using CXX_STANDARD property. But it didn't work. I finally gave up and used add_definitions() and it worked!

The cmake file shows both approaches I tried. ie, add_definitions and the set property approach in the comment (which I tried first but failed to work).

It works with add_definitions() now, but everywhere I turn people recommend using CXX_STANDARD or let cmake use C++11 automatically by requesting a C++11 feature.

So, will this be a problem later on for some reason? And why didn't it work the first time around?

My cmake file:

cmake_minimum_required(VERSION 3.2)

project(testproj CXX)

file(GLOB SRC src/*.cpp)

add_library(testproj SHARED ${SRC})

add_definitions(--std=c++11)
#set(TARGET testproj PROPERTY CXX_STANDARD 11)
#set(TARGET testproj PROPERTY CXX_STANDARD_REQUIRED ON)

# include directories
include_directories(/usr/local/include/mongocxx/v_noabi)
include_directories(/usr/local/include/libmongoc-1.0)
include_directories(/usr/local/include/bsoncxx/v_noabi)
include_directories(/usr/local/include/libbson-1.0)

# library path
link_directories(/usr/local/lib)
target_link_libraries(testproj mongocxx bsoncxx)

if constructor crashes from call to std::make_shared, can gdb show details of crash

In below code, I am calling make_shared<MyClass>, and the constructor of MyClass throws exception. If the core file is available, is it possible to find out the origin of crash [e.g: whether crash was from foo() or fun()] with the help of gdb?

#include <iostream>
#include <memory>
using namespace std;

class MyClass
{
    public:
        MyClass()
        {
            foo();
            fun();
        }

        ~MyClass() { }

        void foo()
        {
            throw("error 1");
        }
        void fun()
        {
            throw("error 2");
        }
};


shared_ptr<MyClass> createMyClass()
{
    return make_shared<MyClass>();
}

int main()
{
    shared_ptr<MyClass> c = createMyClass();
    return 0;
}

backtrace just points to this line:

 29     return make_shared<MyClass>();

backtrace:

Program received signal SIGABRT, Aborted.
0x00007ffff722d5f7 in raise () from /lib64/libc.so.6
Missing separate debuginfos, use: debuginfo-install glibc-2.17-106.el7_2.6.x86_64 libgcc-4.8.5-4.el7.x86_64 libstdc++-4.8.5-4.el7.x86_64

    (gdb) bt
    #0  0x00007ffff722d5f7 in raise () from /lib64/libc.so.6
    #1  0x00007ffff722ece8 in abort () from /lib64/libc.so.6
    #2  0x00007ffff7b329d5 in __gnu_cxx::__verbose_terminate_handler() () from /lib64/libstdc++.so.6
    #3  0x00007ffff7b30946 in ?? () from /lib64/libstdc++.so.6
    #4  0x00007ffff7b30973 in std::terminate() () from /lib64/libstdc++.so.6
    #5  0x00007ffff7b30be9 in __cxa_rethrow () from /lib64/libstdc++.so.6
    #6  0x000000000040121e in std::__shared_count<(__gnu_cxx::_Lock_policy)2>::__shared_count<MyClass, std::allocator<MyClass>>(std::_Sp_make_shared_tag, MyClass*, std::allocator<MyClass> const&) (this=0x7fffffffe178, __a=...) at /usr/include/c++/4.8.2/bits/shared_ptr_base.h:509
    #7  0x00000000004010ba in std::__shared_ptr<MyClass, (__gnu_cxx::_Lock_policy)2>::__shared_ptr<std::allocator<MyClass>>(std::_Sp_make_shared_tag, std::allocator<MyClass> const&) (this=0x7fffffffe170, __tag=..., __a=...) at /usr/include/c++/4.8.2/bits/shared_ptr_base.h:957
    #8  0x0000000000401052 in std::shared_ptr<MyClass>::shared_ptr<std::allocator<MyClass>>(std::_Sp_make_shared_tag, std::allocator<MyClass> const&) (this=0x7fffffffe170,
        __tag=..., __a=...) at /usr/include/c++/4.8.2/bits/shared_ptr.h:316
    #9  0x0000000000400f98 in std::allocate_shared<MyClass, std::allocator<MyClass>>(std::allocator<MyClass> const&) (__a=...) at /usr/include/c++/4.8.2/bits/shared_ptr.h:598
    #10 0x0000000000400ee0 in std::make_shared<MyClass<> > () at /usr/include/c++/4.8.2/bits/shared_ptr.h:614
    #11 0x0000000000400ce3 in createMyClass () at abrt.cpp:29
    #12 0x0000000000400cfe in main () at abrt.cpp:34
    (gdb) q

Lambda expression with empty capture

I've encountered an interesting case (at least for me) when using lambdas and was wondering whether it is a compiler bug or something allowed by the standard feature.

Let's cut to the chase. Having sample code:

const int controlValue = 5;
std::vector<int> vect{ 0, 1, 2, 3 };
const auto result = std::any_of(vect.begin(), vect.end(), [](const int& item)
{
    return item == controlValue;
});

Notice that controlValue variable is not captured by the lambda expression. In the cppreference for lambda expressions it is stated that:

[] - captures nothing

Using VS2015 for compilation of the above code gives an error which is not surprising:

error C3493: 'controlValue' cannot be implicitly captured because no default capture mode has been specified

However, when using MinGW with gcc 4.8.2 same example compiles and works. Some online compilers including gcc 5.4.0, clang 3.8.0 give similar result.

When controlValue looses its const then all tested compilers give the error all expect (that the variable is not captured which is fine).

Which of the compilers is standard compliant in this case? Does this mean that some optimizations or other "hacks" are used for const variables here? Maybe something is captured implicitly? Could anyone explain the situation happening here?

Xcode, C++ and SFML. Library issues

I am trying to compile a simpel code that will show me a window by using Xcode with my mac. Everything seems to work and I get "Build Succeeded". But then nothing happens and I get the message:

dyld: Library not loaded: @rpath/libsfml-audio.2.4.dylib

Referenced from: /Users/zeeshanaslam/Library/Developer/Xcode/DerivedData/test-frpvsmylufuctqaphblszdoivflt/Build/Products/Debug/test

Reason: image not found

I am very new to programming, so please could any one help me with this problem.

My code is:

#include <SFML/Graphics.hpp>


int main(){


    sf::RenderWindow window(sf::VideoMode(640,480),"TEST");

    while (window.isOpen()){

        sf::Event evnt;

        while (window.pollEvent(evnt)){

            if(evnt.type == evnt.Closed)

                window.close();

        }

        window.clear();

        window.display();

    }
}

I am not sure if its the code or Xcode is what causing the problem.

Does the main thread run on blocking threads?

When I started to look into threading in c++11, I thought that .join() was used to make a blocking operation on the main thread and std::async() was used to run non-blocking threads.

This answer explains std:async() pretty well in my opinion. http://ift.tt/2nz22so

But I wanted to understand the join method better. I found several examples like this: http://ift.tt/2oeny8Q Where only 1 thread is created from the main thread.

Then I found this http://ift.tt/1dBg4Dv

Snippet of Code from site:

#include <iostream>
#include <thread>

static const int num_threads = 10;

//This function will be called from a thread

void call_from_thread(int tid) {
    std::cout << "Launched by thread " << tid << std::endl;
}

int main() {
    std::thread t[num_threads];

    //Launch a group of threads
    for (int i = 0; i < num_threads; ++i) {
        t[i] = std::thread(call_from_thread, i);
    }

    std::cout << "Launched from the main\n";

    //Join the threads with the main thread
    for (int i = 0; i < num_threads; ++i) {
        t[i].join();
    }

    return 0;
}

The part I'm curious about this this part right here:

//Join the threads with the main thread
for (int i = 0; i < num_threads; ++i) {
    t[i].join();
}

If the main thread stops to wait until .join() is complete, how can the loop run to join more threads? The fact it works is great! But, why does it work?

  1. Why does it work this way?
  2. Main thread joins 1st thread.
  3. Main thread waits until 1st thread finishes.
  4. 1st thread finishes.
  5. Main thread continues in for loop and joins 2nd thread.
  6. Main thread waits until 2nd thread finishes.
  7. ... ... ...

If it keep cycling through the for loop when does the main thread actually get blocked to wait?

Is it required to keep promise valid when using its future?

Say I have a function that enqueues a job and returns an std::future that will be set when the job is done. Is it required to keep the corresponding std::promise valid?

std::vector<std::promise<void>> jobs;
std::mutex jobMutex;

std::future<void> EnqueueJob()
{
    std::lock_guard<std::mutex> lock(jobMutex);
    jobs.emplace_back();
    return jobs.back().get_future();
}

// async job loop
void DoJobs()
{
    while(true)
    {
        // (...) wait for a job to be ready

        // finish jobs
        std::lock_guard<std::mutex> lock(jobMutex);
        // (...)
        for (auto& promise : jobs)
            promise.set_value();
        jobs.clear();
    }
}

If I enqueue a job and wait for its future later on it is possible that the corresponding promise is already cleared from the job vector. Is this okay? If not, what would be a good way to solve this problem?

I am unable to find an answer using promise's and future's documentation.

Error occurred when passing r-value reference to r-value reference parameter [duplicate]

This question already has an answer here:

I have code

void print(string &&str) {
   cout << str << endl;
}
int main() {
   string tmp("Hello");
   string&& str = move(tmp);
   //print(move(str));
   print(str);
   return 0;
}

After compiling I get error: cannot bind rvalue reference of type 'std::__cxx11::string&&' to lvalue of type 'std::__cxx11::string'.

But str is r-value reference to r-value(isn't it?), so passing it into print makes sense I believe. Why this error occurred?

How can a struct inherits itself?

template <bool condition>
struct when;

template <typename It, typename = void>
struct at_impl : at_impl<It, when<true>> { };

struct at_t {
    template <typename Xs, typename N>
    constexpr decltype(auto) operator()(Xs&& xs, N const& n) const;
};

constexpr at_t at{};

int main()
{
}

How could this program compiled? How can a struct inherits itself?! I don't know what's going on here. Is this a new feture in c++?

What exactly the specifier final does in C++? [duplicate]

This question already has an answer here:

I read about final specifier on cppreference, which is used to prevent virtual function from being overridden by derived classes. If we don't want to overload function, then why did we define the function to be virtual. I still don't have a full grasp of what exactly the specifier final does? How does it work? And when should I use it?

struct Base {
        virtual void func() const final;    // do not override
        virtual void g();
    };

    struct Derived : Base {
        void func() const;  // error: D::f attempts to override final B::f
        void g();       // OK
    };

Race condition in Producer-Consumer: limit notifications to when condition variable is waiting

I've implemented a simple Producer-Consumer message queue.

#include <chrono>
#include <iostream>
#include <thread>
#include <mutex>
#include <deque>


#define MESSAGE_QUIT 1


struct MessageQueue
{
    std::deque<int> message_ids;
    std::mutex mutex;
    std::condition_variable condition_variable;
};


void SleepFor(int time_in_millis)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(time_in_millis));
}


void ProcessMessage(int message_id)
{
    std::cout << "Processing Message #" << message_id << '\n';
}


void Producer(MessageQueue *messages)
{
    for (int message_id = 10; message_id >= MESSAGE_QUIT; --message_id) {
        std::unique_lock<std::mutex> guard(messages->mutex);    
        messages->message_ids.push_back(message_id);            
        guard.unlock();
        messages->condition_variable.notify_one();
        SleepFor(200);
    }
}


void Consumer(MessageQueue *messages)
{
    int next_message_id = -1;

    while (next_message_id != MESSAGE_QUIT) {
        std::unique_lock<std::mutex> guard(messages->mutex);
        messages->condition_variable.wait(guard);

        if (!messages->message_ids.empty()) {
            next_message_id = messages->message_ids.front();
            messages->message_ids.pop_front();
            guard.unlock();
            ProcessMessage(next_message_id);
        }   
    }
}


int main()
{
    MessageQueue messages;

    std::thread producer_thread(&Producer, &messages);
    std::thread consumer_thread(&Consumer, &messages);

    producer_thread.join();
    consumer_thread.join();
}

The race condition: in some cases, the condition variable is calling notify_one() in the producer thread while it is not in the waiting state in the consumer thread. How would you solve this? I am not considering the case of spurious waking for now.

Why are functions in

This question already has an answer here:

I have the following basic code that creates a vector and tries finding an element in it. I noticed that you don't need to specify the std:: namespace to call find and was wondering if there was any particular reason the functions in <algorithm> are not wrapped in namespace std? I ask because I was recently writing a find method and encountered an ambitious compiler error.

Isn't the whole point of namespaces to avoid this sort of thing?

#include <iostream>
#include <vector>
#include <algorithm>

using std::cout;    using std::endl;
using std::vector;  using std::string;


int main() {
    std::vector<int> v = {1,5,6,9,3,4};
    auto i = find(v.begin(), v.end(), 3);       // why does this work without std:: at the beginning
    cout << "Output: " << *i << endl;
}

Container of pointers to template class

I'm trying to make a class (ParametersHolder) that can contain different named parameters (Parameter<T>). The ParametersHolder has an std::unordered_map container holding my parameters. To make this work, I had to derive Parameter<T> from an empty ParameterBase class and I dynamically cast ParameterBase to Parameter<T> when I want to get a parameter with the right type. Here is the code:

ParametersHolder.hpp

...
#include "Parameter.hpp"

class ParametersHolder {

  std::unordered_map<std::string, std::shared_ptr<ParameterBase>> parameters;

  public:

    bool paramExists(std::string name) {
      return parameters.find(name) != parameters.end();
    }

    template<typename T>
    std::shared_ptr<Parameter<T>> getOrCreate(std::string name, int dims = 1) {
      if (paramExists(name)) {
        return getParam<T>(name);
      }
      return create<T>(name, dims);
    }

    template<typename T>
    std::shared_ptr<Parameter<T>> create(std::string name, int dims = 1) {
      if (paramExists(name)) throw std::runtime_error("Trying to create parameter '" + name + "' but it already exists");
      auto param = std::make_shared<Parameter<T>>(dims);
      parameters[name] = param;
      return param;
    }

    template<typename T>
    std::shared_ptr<Parameter<T>> getParam(std::string name) {
      if (!paramExists(name)) throw std::runtime_error("Parameter '" + name + "' doesn't exist");
      auto param = std::dynamic_pointer_cast<Parameter<T>>(parameters[name]);
      if (param == nullptr) throw std::runtime_error("Parameter '" + name + "' is not a(n) " + boost::typeindex::type_id<T>().pretty_name());
      return param;
    }

};

Parameter.hpp

class ParameterBase {
  public:
    virtual ~ParameterBase() {}
};

template<typename T>
class Parameter : public ParameterBase {

  std::vector<T> data;

  public:

    explicit Parameter(int dim = 1) : data(dim) {}

    T getValue(int dim = 1) {
      dimCheck(dim);
      return data[dim - 1];
    }

    void setValue(T value, int dim = 1) {
      dimCheck(dim);
      data[dim - 1] = value;
    }

  private:
    void dimCheck(int dim) {
      if (dim > data.size()) {
        auto errorMsg = "Trying to access dimension " + std::to_string(dim)
          + " but parameter has only " + std::to_string(data.size()) + " dimensions";

        throw std::runtime_error(errorMsg); 
      }
    }
};

To use this code I can do that:

auto paramsHolder = std::make_shared<ParametersHolder>();
auto filename = paramsHolder->create<std::string>("filename");
filename->setValue("untitled.txt");

...

auto param = paramsHolder->getParam<std::string>("filename");
std::cout << param->getValue() << std::endl;

This works fine but having an empty ParameterBase feels odd. Is there another way to achieve that? I read about boost::any, but I'm not sure this is the right use case. And if it is, I don't know what the type signature of the unordered_map should be among these:

std::unordered_map<std::string, std::shared_ptr<Parameter<boost::any>>>
std::unordered_map<std::string, std::shared_ptr<boost::any>>
std::unordered_map<std::string, boost::any>

File not opening second time in c++

I am trying to open a file using this code which will be called multiple time. First time the file is opening but when this is called for the second time, I am getting some error on the fp1.open.... line, which is:

Error in `/home/prosun/Desktop/workspace/fight/Default/fight': corrupted double-linked list: 0x0000000000675310

The code:

void Writedata::write_file(){

    ofstream fp1;
    int i;

    fp1.open ("output/data.txt"), ios::out | ios::app);
    for(int i = 0; i < 10; i++){
         cout.width(10); fp1 << i << endl;
    }
    fp1.close();
}

Please help me solve this issue.

std::move with && (rvalue reference) as a member function return type [duplicate]

I just want to initialize a member data oneObj of class Two as below which compiles fine. I would like to know whether it is advisable to use std::move and && together to initialize an object or just pass the oneObj as a reference to InitObjOne as follows InitObjOne(One & obj) and initialize it. is there any advantage over another. Please clarify.

Note: The InitObjOne need to perform few actions for creating an object of One, I've just given a skeleton of the functionalities here.

#include <iostream>
using namespace std;

class One
{
    public:
    int x;
};

class Two
{
   public:
   Two();

   private:
   One oneObj;
   One && InitObjOne();
};

Two::Two() : oneObj(InitObjOne())
{

}

One && Two::InitObjOne()
{
    One aObjOne;
    return std::move(aObjOne);
}

int main() 
{
    Two two;
    return 0;
}

Is there a class/template in std library to perform a task when out of scope?

We have some resource, which need to be manually released. Except explicitly writing a RAII wrapper for managing its resource, is any built-in template or class in std library to automatically perform a lambda task?

{
    auto resource = InitResource();        
    GuardedTask task ([&resource]{ FreeUp(resource); }); // Simply bind a clean up lambda
    ...
    if(failed_condition_met) { return false; } // Free up
    ...
    if(another_failed_condition_met) { return false; } // Free up

} // Free up

The class may behavior like the following, but I am wondering that wheel may be already built in std library, or I should write my own one.

struct GuaredTask
{
    std::function<void()> task;
    GuaredTask(std::function<void()> f): task(f) {}
    ~GuaredTask(){ task(); }
};

Force CRTP inheritance

Is it possible to detect that a CRTP base class is templated with the exact same class deriving from base?

I've something like

class GeneratedA : public RegisteredEvent<GeneratedA>;
class GeneratedB : public RegisteredEvent<GeneratedB>;

which works but is it possible to trigger a compile error if the interface is used like this:

class GeneratedB : public RegisteredEvent<GeneratedA>;

Thank you

Input validation to only accept numbers

I'm creating program and it should only be allowed to accept numbers if a letter is entered it should re-ask the use to enter a number. When i run the code i get an error saying there's a problem with the break heres a copy of my code

#include <iostream>
using namespace std;

class Triangle
{
    private:
        double base;
        double height;
    public:
        void setBase(double);
        void setHeight(double);
        double getBase() const;
        double getHeight() const;
        double getArea() const;
};

void Triangle::setBase(double b)
{
    base = b;
}

void Triangle::setHeight(double hg)
{
    height = hg;
}

double Triangle::getBase() const
{
    return base;
}

ouble Triangle::getHeight() const
{
    return height;
}

double Triangle::getArea() const
{
    return .50 *(base * height);
}

int main()
{
    double number; 
    double totalArea;
    Triangle one; 
    Triangle two;
    Triangle three;

    do
    {
        cout << "What is the base of Triangle One:"; 
        cin >> number;

        one.setBase(number); 
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle One:"; 
        cin >> number;
        one.setHeight(number); 
            cout << "You have entered " << number << " for the height of the triangle.\n";

            cout << "What is the base of Triangle Two: "; 
        cin >> number;
        two.setBase(number); 
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle Two:"; 
        cin >> number;
        two.setHeight(number); 
            cout << "You have entered " << number << " for the height of the triangle.\n";

            cout << "What is the base of Triangle Three:"; 
        cin >> number;
        three.setBase(number); 
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle Three:"; 
        cin >> number;
        three.setHeight(number); 
             cout << "You have entered " << number << " for the height of the triangle.\n";
    }   
    while (0); 
    {
        if (cin >> number) 
        {
            break;
        } 
        else 
        {
            cout << "Invalid Input! Please input a numerical value." << endl;
                    cin.clear();
            while (cin.get() != '\n') ; 
        }
    }


    totalArea = one.getArea() + two.getArea() + three.getArea(); 

    cout << "The total area of the three triangles is " << totalArea << endl; 

    return 0; 

}

Here's the error im receiving

Choosing delimiters for multiple regex string in one string [c++11]

Firstly, those regex are for matching table columns, i.e. FirstName, LastName, EmployeeId, XXX_Name, YYY_Name, etc.

I need to construct a single string which contains multiple regex like this:

pattern1,pattern2,~pattern3

the ',' is for delimeter regex patterns, and '~' means not matching.

So above string means:

  1. One of the table columns matches pattern1, and
  2. One of the table columns matches pattern2, and
  3. None of the table columns matches pattern3

But, ',' is one of the special chars for regex, I'm not sure if '~' is also.

Could you suggest what're the best candidates for the delimiters? Or an alternative solution for this?


I'm considering '\n' and ';'. '\n' I know it should be safe enough.

But ';' not sure if it is one of the regex special char, do you know?

I checked this doc Regular Expression Reference, but even ',' ({m,n} case) is not documented there.

mercredi 29 mars 2017

Initializer list of RValues

Right now I have a class with only one constructor

ShaderProgram(std::initializer_list<std::reference_wrapper<const Shader>> shaders);

I'm using a reference wrapper because I can't have an initializer_list of references and I can't copy

This code works

    Shader v{ Shader::Type::Vertex, readFile("res/simple.vert") };
    Shader f{ Shader::Type::Fragment, readFile("res/simple.frag") };
    ShaderProgram shader{ v, f };

But this does not

    ShaderProgram shader{ 
        Shader { Shader::Type::Vertex, readFile("res/simple.vert") },
        Shader { Shader::Type::Fragment, readFile("res/simple.frag") }
    };

What should I be covering here? I suppose I'm missing some kind of constructor to handle rvalues but I can't seem to make it work

Makefile with two C++ files : How can I choose the file to compile?

Let's say I have two C++ main files, project.cpp, and projectgraph.cpp. They both use the same header file functions.h, as well as the file functions.cpp.

To compile project.cpp, I'm using the following makefile :

CXX = g++
CXXFLAGS= -std=c++11 -w -Wall -g 

project: project.o functions.o 
    $(CXX) $(CXXFLAGS) -o project projet.o functions.o 

functions.o: functions.h

clean:
    rm -rf *.o

I would like to be able to choose between project.cpp and projectgraph.cpp to be compiled using the make command in the terminal. For example :

  • If I type make in the terminal : project.cpp would be compiled.
  • If I type make graph in the terminal : projectgraph.cpp would be compiled.

How can I change the makefile to get this result ?

Thanks !

Why there is no data race?

I am reading Bjarne's FAQ on Memory Model, here is a quote

So, C++11 guarantees that no such problems occur for "separate memory locations.'' More precisely: A memory location cannot be safely accessed by two threads without some form of locking unless they are both read accesses. Note that different bitfields within a single word are not separate memory locations, so don't share structs with bitfields among threads without some form of locking. Apart from that caveat, the C++ memory model is simply "as everyone would expect.''

However, it is not always easy to think straight about low-level concurrency issues. Consider:

start with x==0 and y==0

if (x) y = 1; // Thread 1

if (y) x = 1; // Thread 2

Is there a problem here? More precisely, is there a data race? (No there isn't).

My question is, why there is no data race? It is obvious to me that there apparently is a data race since thread 1 is a writer for y while thread 2 is a reader for y, and similarly for x.

Using Wt::Dbo cause MySQL prepared statement leak

I have a project that is using Wt::Dbo as object relational database management with MySQL. Since about a week I've remarked a leak in database prepared statement. Previously this project was using SQLite.

I tried different flush() without success and can't figure out exactly what is causing this leak, but for sure when prepared statements grow at a certain point, MySQL stop answering.

Here is how I monitor the leaked prepared statement :

$ mysql -uroot -p -e "SHOW SESSION STATUS LIKE '%prepare%';" | grep stmt_count
Enter password: 
Prepared_stmt_count 260

The leaked statement are cleared when program is restarted.

All database operations are centralized inside a class called DataBase, here are some functions that are known to leak :

DataBase::initialize()

void DataBase::initialize(void)
{
    m_oMutex.lock();

    if(!m_bInitialized)
    {
        m_bInitialized = true;

        try
        {
            m_oSessionConfigurations.setConnection(*new Wt::Dbo::backend::Sqlite3("databases/configuration.db"));
            m_oSessionConfigurations.mapClass<InformationSite>("informationsite");

            m_oSessionConfigurations.createTables();
        }
        catch(std::exception &e)
        {
            ajouterLog("error",std::string("DataBase::initialize() : ") + e.what());
        }

        try
        {
            #if defined(DATABASE_TYPE_SQLITE)
                Wt::Dbo::backend::Sqlite3 *pBackend = new Wt::Dbo::backend::Sqlite3("databases/dataBase.db");
            #elif defined(DATABASE_TYPE_MYSQL)
                Wt::Dbo::backend::MySQL *pBackend;

                try
                {
                    pBackend = new Wt::Dbo::backend::MySQL(DATABASE_NAME,DATABASE_USERNAME,DATABASE_PASSWORD,"localhost");
                }
                catch(Wt::Dbo::Exception &e)
                {
                    ajouterLog("error",std::string("DataBase::initialize() : ") + e.what());

                    // If MySQL is not available, this cause issue to program until restart.
                    exit(1);
                }
            #endif

            pBackend->setProperty("show-queries","true");

            m_oSession.setConnection(*pBackend);

            m_oSession.setFlushMode(Wt::Dbo::FlushMode::Auto);

            m_oSession.mapClass<RFNode>("rfnode");
            m_oSession.mapClass<NodeMeasure>("nodemeasure");

            // Override the default InnoDB from Wt, MyISAM is easier to repair in case of hardware failure with database corruption
            #if defined(DATABASE_TYPE_MYSQL)
                try
                {
                    Wt::Dbo::Transaction oTransaction(m_oSession);

                    m_oSession.execute("SET default_storage_engine=MYISAM;");

                    oTransaction.commit();
                }
                catch(Wt::Dbo::Exception &e)
                {
                    ajouterLog("error",std::string("DataBase::initialize() : ") + e.what());
                }
            #endif

            m_oSession.createTables();
        }
        catch(Wt::Dbo::Exception &e)
        {
            ajouterLog("error",std::string("DataBase::initialize() : ") + e.what());
        }
    }

    m_oMutex.unlock();
}

DataBase::addNodeMeasure()

void DataBase::addNodeMeasure(NodeMeasure *p_pItem)
{
    m_oMutex.lock();

    try
    {
        Wt::Dbo::Transaction oTransaction(m_oSession);

        Wt::Dbo::ptr<NodeMeasure> oItem = m_oSession.add(p_pItem);

        oItem.flush();

        oTransaction.commit();
    }
    catch(std::exception &e)
    {
        ajouterLog("error",std::string("Exception DataBase::addNodeMeasure() : ") + e.what());
    }

    m_oMutex.unlock();

    printPreparedStatementCount("DataBase::addNodeMeasure()");
}

DataBase::updateNode()

void DataBase::updateNode(RFNode *p_pItem)
{
    printPreparedStatementCount("DataBase::updateNode() Before");

    m_oMutex.lock();

    try
    {
        Wt::Dbo::Transaction oTransaction(m_oSession);

        Wt::Dbo::ptr<RFNode> oItem = m_oSession.find<RFNode>().where("mac = ?").bind(p_pItem->mac);

        oItem.modify()->zone                    = p_pItem->zone;
        oItem.modify()->subZone                 = p_pItem->subZone;
        oItem.modify()->unit                    = p_pItem->unit;
        oItem.modify()->pwm                     = p_pItem->pwm;
        oItem.modify()->led                     = p_pItem->led;
        oItem.modify()->network                 = p_pItem->network;
        oItem.modify()->lastContact             = p_pItem->lastContact;
        oItem.modify()->ioConfiguration         = p_pItem->ioConfiguration;
        oItem.modify()->networkAddress          = p_pItem->networkAddress;
        oItem.modify()->type                    = p_pItem->type;
        oItem.modify()->functionality           = p_pItem->functionality;
        oItem.modify()->transmitPowerLevel      = p_pItem->transmitPowerLevel;
        oItem.modify()->lastNetworkRoute        = p_pItem->lastNetworkRoute;
        oItem.modify()->lastNetworkJumpsCount   = p_pItem->lastNetworkJumpsCount;
        oItem.modify()->lastRequestDuration     = p_pItem->lastRequestDuration;
        oItem.modify()->hardwareVersion         = p_pItem->hardwareVersion;
        oItem.modify()->softwareVersion         = p_pItem->softwareVersion;

        oItem.flush();

        oTransaction.commit();
    }
    catch(std::exception &e)
    {
        ajouterLog("error",std::string("Exception DataBase::updateNode() : ") + e.what());
    }

    m_oMutex.unlock();

    printPreparedStatementCount("DataBase::updateNode() After");
}

DataBase::getNodeMeasures()

std::vector<NodeMeasure> DataBase::getNodeMeasures(std::string p_sMAC, int p_nType, Wt::WDateTime p_oStartDate, Wt::WDateTime p_oEndDate, std::string p_sOrder, int p_nLimit)
{
    std::vector<NodeMeasure> lNodeMeasures;

    m_oMutex.lock();

    try
    {
        Wt::Dbo::Transaction oTransaction(m_oSession);

        std::string sWhereClause = "", sOrderClause = "";

        if(!p_sMAC.empty())
        {
            if(!sWhereClause.empty())
            {
                sWhereClause += " AND ";
            }

            sWhereClause += "mac = '" + p_sMAC + "'";
        }

        if(p_nType != -1)
        {
            if(!sWhereClause.empty())
            {
                sWhereClause += " AND ";
            }

            sWhereClause += "type = " + std::to_string(p_nType);
        }

        if(p_oStartDate.isValid())
        {
            if(!sWhereClause.empty())
            {
                sWhereClause += " AND ";
            }

            // When not using type, we usually want nodes measures (not external temperature), so we want to find them using batchDate instead of date
            sWhereClause += (p_nType != -1 ? "date" : "batchDate");
            sWhereClause += " >= '";
            sWhereClause += p_oStartDate.toString("yyyy-MM-ddTHH:mm:ss").toUTF8();
            sWhereClause += "'";
        }

        if(p_oEndDate.isValid())
        {
            if(!sWhereClause.empty())
            {
                sWhereClause += " AND ";
            }

            // When not using type, we usually want nodes measures (not external temperature), so we want to find them using batchDate instead of date
            sWhereClause += (p_nType != -1 ? "date" : "batchDate");
            sWhereClause += " <= '";
            // Add one second because SQLite have microseconds, and we must include results no matter microseconds field
            sWhereClause += p_oEndDate.addSecs(1).toString("yyyy-MM-ddTHH:mm:ss").toUTF8();
            sWhereClause += "'";
        }

        if(!p_sOrder.empty())
        {
            sOrderClause = " ORDER BY " + p_sOrder;
        }

        std::string sQuery = "";

        if(!sWhereClause.empty())
        {
            sQuery += " WHERE ";
            sQuery += sWhereClause;
        }

        if(!sOrderClause.empty())
        {
            sQuery += sOrderClause;
        }

        //std::cout << "**************************************************************************" << std::endl;
        //std::cout << sQuery << std::endl;
        //Wt::WDateTime oStart = Wt::WDateTime::currentDateTime();

        if(Configuration::getParameter(Configuration::PARAMETER_DEBUG).getBooleanValue())
        {
            ajouterLog("debug","DataBase::getNodeMeasures() " + sQuery);
        }

        // TEST : find vs query
        Wt::Dbo::collection<Wt::Dbo::ptr<NodeMeasure>> lMeasures = m_oSession.find<NodeMeasure>(sQuery).limit(p_nLimit).resultList();

        // TODO : Get it cleaner... can't use Wt::Dbo::ptr outside transaction.
        for(Wt::Dbo::collection<Wt::Dbo::ptr<NodeMeasure>>::const_iterator pMeasure = lMeasures.begin();pMeasure != lMeasures.end();pMeasure++)
        {
            lNodeMeasures.push_back(
                    NodeMeasure(
                            (*pMeasure)->mac,
                            (*pMeasure)->type,
                            (*pMeasure)->date,
                            (*pMeasure)->batchDate,
                            (*pMeasure)->value
                    )
            );

            (*pMeasure).flush();
        }

        //lNodeMeasures = m_oSession.find<NodeMeasure>(sQuery).limit(p_nLimit).resultList();

        //std::cout << "Result : " << lNodeMeasures.size() << " in " << oStart.secsTo(Wt::WDateTime::currentDateTime()) << "s" << std::endl;
        //std::cout << "**************************************************************************" << std::endl;

        oTransaction.commit();
    }
    catch(std::exception &e)
    {
        ajouterLog("error",std::string("Exception DataBase::getNodeMeasures() : ") + e.what());
    }

    m_oMutex.unlock();

    printPreparedStatementCount("DataBase::getNodeMeasures()");

    return lNodeMeasures;
}

Wrapping container for containers providing other interface

I want to create universal "wrapper" for stl containers, something like:

template<template <typename, typename...> class Container = std::vector >
class ContainerWrapper{
  add();
  size();
  find();
  resize();
  sort(); 
  /**/
}

+iterators. I would want member functions to have different implementations, depending on Container provided methods. Is C++ template system enough to create this? Is this even possible, using only standard (no boost, no messing with preprocessor)?

I know how to do it the hard way - write template specialization for each stl container. But I would want it to work with other containers too, and also i'm looking for more universal way to do it.

Also, what is better here? Inheriting from Container or having Container as component?

Cache locality with unique_ptr

I have a vector of custom classes (std::string just for example).

The vector is large and I iterate through often, so I rely on cache locality.

I also have one raw pointer which points at one of the vector elements.

Now is the trick:

The vector is sorted from time to time, so the raw pointer loose the actual pointed element value, and will point to some random element value.

Here is an example to illustrate the same:

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <memory>

using namespace std;

int main()
{

    vector<string> v = {"9","3", "8", "7", "6", "5", "1", "4", "2"};

    string* rs = &v[7]; //point to the 7th element

    for (size_t i = 0; i < v.size(); ++i)
        cerr << v[i];
    cerr << endl;
    cerr << "Referenced string: " << rs->c_str() << endl;

    cerr << "Sort ..." << endl;
    sort(v.begin(), v.end(), [](const string& a, const string& b)
    {
        if (a < b)
            return true;
        else
            return false;
    }
    );

    for (size_t i = 0; i < v.size(); ++i)
        cerr << v[i];
    cerr << endl;
    cerr << "Referenced string: " << rs->c_str() << endl;

    cin.get();
    return 0;

}

Output:

938765142
Referenced string before sort : 4
Sort ...
123456789
Referenced string after sort : 8

Since I wish the rs pointer to keep pointing to the 7th element value (which is 4) even after the sort, I came up with the following solution (vector of pointers):

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <memory>

using namespace std;

int main()
{


    vector<unique_ptr<string>> v;
    v.resize(9);
    v[0] = make_unique<string>("9");
    v[1] = make_unique<string>("3");
    v[2] = make_unique<string>("8");
    v[3] = make_unique<string>("7");
    v[4] = make_unique<string>("6");
    v[5] = make_unique<string>("5");
    v[6] = make_unique<string>("1");
    v[7] = make_unique<string>("4");
    v[8] = make_unique<string>("2");

    string* rs = v[7].get();        

    for (size_t i = 0; i < v.size(); ++i)
    cerr << v[i]->c_str();
    cerr << endl;
    cerr << "Referenced string before sort: " << rs->c_str() << endl;


    cerr << "Sort ..." << endl;
    sort(v.begin(), v.end(), [](const unique_ptr<string>& a, const unique_ptr<string>& b)
    {
    if (*a < *b)
    return true;
    else
    return false;
    }
    );



    for (size_t i = 0; i < v.size(); ++i)
    cerr << v[i]->c_str();
    cerr << endl;
    cerr << "Referenced string after sort: " << rs->c_str() << endl;


    cin.get();
    return 0;

}

Output:

938765142
Referenced string before sort: 4
Sort ...
123456789
Referenced string after sort: 4

While this latter solution works, there is a price: I have lost the cache locality of my vector, since I store pointers in it, rather than the actual objects.

Is there a way to maintain cache locality (e.g.: store my actual objects in the vector), and somehow manage to rs pointer to keep track where its pointed value wander around due to the sorts? Or from the other perspective, is there a way to achieve cache locality with the vector of pointers?

Remove sql table after x days

I am looking for a way for my system made in C ++ to remove old sqls tables after 90 days, I searched but did not find anything related.

The names of my tables are generated according to the days, for example 20170323

Now the way to remove I can not think of anything that can be done

How to make_shared count times, with different areas allocated without recur to a loop?

How to make_shared count times, with different areas allocated without recur to a loop?

I have the following code:

for( unsigned int count = 0; count < demandedSize; ++count  )
{   
   m_connectionList.push_back( std::make_shared< Foo >( m_ip, m_port )); 
}

How to shorten this without a loop?

I know std::vector receaves a second argument as const T&, but in that case all shared_ptrs points to the same address (value is copied).

std::vector< std::shared_ptr<Foo> > vet( demandedSize, std::make_shared<Foo>( m_ip, m_port ) );

How to execute make_shared count times, with different areas allocated as result without recur to a loop

Strange behavior multithreading openMP visual studio 2015

I encountered weird behavior using visual studio 2015 due to multithreading, code does not spawn threads, even when explicete ask to.

    std::vector<std::thread> Pool;
    Pool.reserve(std::thread::hardware_concurrency());

    int max = ImageB_spline.rows() % std::thread::hardware_concurrency();
    max = ImageB_spline.rows() - max;
    int step = max / std::thread::hardware_concurrency();

    for (int thread = 0; thread < std::thread::hardware_concurrency() - 1; ++thread) {
        Pool.push_back(std::thread([](Eigen::Array<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor >& _ImageB_spline, Eigen::Matrix<std::complex<double>, 1, Eigen::Dynamic, Eigen::RowMajor> _X_Freq_kernel, int start, int stop) {
            //work
        }, std::ref(ImageB_spline), X_Freq_kernel, step *thread, step *thread + 1));
    }

    Pool.push_back(std::thread([](Eigen::Array<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor >& _ImageB_spline, Eigen::Matrix<std::complex<double>, 1, Eigen::Dynamic, Eigen::RowMajor> _X_Freq_kernel, int start, int stop) {
        //work
    }, std::ref(ImageB_spline), X_Freq_kernel, std::thread::hardware_concurrency() - 1, ImageB_spline.rows()));

    for (int iter = 0; iter < Pool.size(); ++iter) {
        Pool[iter].join();
    }

it create 8 threads with different id but it isn't executed int parallel, same as using openMP ( in language settings I enable openMP, and in command line flag is present). Still no parallelism.

#pragma openmp parallel for firstprivate(fft,X_Freq_kernel,X_Freq_Row_Conv) num_threads(4)
    for (int iI = 0; iI < ImageB_spline.rows(); ++iI)
    {
        //work
    }

I resolve to use

        std::thread F1([](Eigen::Array<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor >& _ImageB_spline, Eigen::Matrix<std::complex<double>, 1, Eigen::Dynamic, Eigen::RowMajor> _X_Freq_kernel, int start, int stop) {
        //work
    }, std::ref(ImageB_spline), X_Freq_kernel, 0, 999);

    std::thread F2([](Eigen::Array<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor >& _ImageB_spline, Eigen::Matrix<std::complex<double>, 1, Eigen::Dynamic, Eigen::RowMajor> _X_Freq_kernel, int start, int stop) {
        //work
    }, std::ref(ImageB_spline), X_Freq_kernel, 1000, 1999);


    std::thread F3([](Eigen::Array<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor >& _ImageB_spline, Eigen::Matrix<std::complex<double>, 1, Eigen::Dynamic, Eigen::RowMajor> _X_Freq_kernel, int start, int stop) {
        //work
    }, std::ref(ImageB_spline), X_Freq_kernel, 2000, 2500);


    F1.join();
    F2.join();
    F3.join();

And now its executing in parallel, and i don't see reason why...

Variadic template argument deduction/substitution failed, metaprogramming

Im attempting to create a recursive template function, however I keep getting the error:

no matching function for call to meuPrint(int&, Separator&, string&)

while also receiving:

candidate: template string meuPrint(U ..., Separator&,string&).

struct Separator {};    

template<class ...U>
string meuPrint( U ...b , Separator &placeholder , string& text )
{//end
    char buffer[200];
    sprintf( buffer , text.c_str() , b... );
    return buffer;
}
template<class ...T, class ...U>
string meuPrint( U ...b , Separator &placeholder , string& text , string value , T ...a )
{//string
    return meuPrint( b... , to_lower( value ) , placeholder , text , a... );
}

template<class V, class ...T, class ...U>
string meuPrint( U ...b , Separator &placeholder , string& text , V value , T ...a )
{//middle
    return meuPrint( b... , value , placeholder , text , a... );
}

template<class ...T>
string meuPrint( std::string _text , T ...a )
{//start
    Separator placeholder;
    return meuPrint( placeholder , _text , a... );
}

int main( int n , char** args )
{
    string o = meuPrint(  string( "hello %i world" )  ,  8 );
    std::cout << o << std::endl;
    return 0;
}

The goal here isnt necessarily to lowercase the parameters, but to test a concept. I dont understand why the compiler keeps failing to deduce while telling me some valid candidates afterwards.

storing pointer to member function does not work for clang++

when i use clang++ i can only call the pointer-to-member function i can't cast it or assign it to a variable to call i when needed (i want to store this variable to an array of functions) but with g++ i can do that take this for example

class Base {
    public:
        typedef void (Base::*A)();
        virtual void some_func() = 0;
};
class B: public Base {
    public:
        void some_func() {
            return
        }
};
int main() {
    B b;
    auto h = (Base::A)&Base::some_func;
    typedef void (*my_function)();
    auto some_func = (my_function)(b.*h);
    some_func();
    return 0;
}

with g++ this do compile and run, but with clang++ i get reference to non-static member function must be called; did you mean to call it with no arguments? ( please note that i can't use any std::x functions in my code because the code run on bare metal

Calling Python member functions from C++

I need to test the feasibility of calling Python member functions from within C++. I have calling of non-member functions working, but cannot see how to get a reference to the created Python object from C++ who's member I need to call.

Can anyone advise?

Function doing integer comparison in C++

I am writing a variadic template function which compare multiple integer (like "1 < int_var <= DEFINED_VAR").

For that, I need the prototype of the operator function. I thought it would be:

template<typename T> bool (*comparison_operator)(T, T)

But it does not work. I guess it is because this is not this function that is used for primitive type. I found the "std::less" (and the others operators) online, but it is C++14 and I am stuck with C++11.

Is there a way to do it ? Because, for the moment, the only thing I can think of is replacing every comparison operator by a custom function.

Thanks.