create vector with new elements

so I have the following

vector<vector< tuple<string, double>*>*>* graph;

a 2d vector, with a tuple of string and double. I want to initialize the graph(2d vector) with a certain size and a new vector< tuple<string, double>*>, in each of the element of the big (outside)vector

and I used the following line

graph = new vector<vector<tuple<string, double>*>*>(67, new vector< tuple<string,double>*>());

This thing works but when I tried to free it I found out that all new vectors I created are of the same vector. meaning, all the elements point to the same vector. I get why this is happening but is there a way of initialize all the vectors without having to do the for loop, ie

for(int i....)
    graph->push_back(new vector< tuple<string,double>*>);

Answer

Problem summary:

In the line

graph = new vector<vector<tuple<string, double>*>*>(67, new vector< tuple<string,double>*>());

constructor 3 of std::vector is used (reference) This will evaluate new vector<tuple<string,double>*>() once, then create a vector with 67 copies of this pointer.

Solution:

Don’t use pointers unless you have a really good reason to do so. Use

vector<vector<tuple<string, double>>> graph;

then you could simply do

graph.resize(67);

to insert 67 default constructed values. No pointers needed.

Maybe you are used to languages where new is frequently used, but you shouldn’t do that in C++. std::vector and std::string are fairly small objects that manage an underlying dynamic array. Creating pointers to them is usually not what you want and might also decrease performance.

Leave a Reply

Your email address will not be published. Required fields are marked *