In my question a vector means a vector of structures of the form
struct node
{string key;
int a,b; };
I want to code up the following: Given a user specified number say d I want to create a sequence of d vectors v_1, v_2, ...v_d.
v_1 is created from user data, and v_i from v_(i-1) for i>=2 .
The size of v_i is the number of nodes in v_(i-1) with distinct key fields.
The a and b fields of the v_i nodes are calculated according to some black box algorithm from those of v(i-1)
How should I code this up efficiently in C++?
Should I use a map of the form
map<int, vector<nodes>> where the int field varies between 1 and d??
Thank you!
P:S: I guess one could code up a solution, using new operator and some pointer gymnastics, instead of using vectors. But I would like to have as pointer free a solution as possible.
Use
std::vector<std::vector<node> >, but usevector::reserve()intelligently so as to avoid reallocations:The only vector with wasted space and time is v[0].
EDIT: the call to
std::copyabove is a loop-less idiom roughly equivalent tostd::copytakes three arguments. The first two are input iterators which define the range from which we copy, while the third is an output iterator defining the destination.Specifically,
istream_iterator<node>(std::cin)is an input iterator which, when dereferenced, reads the nextnodefrom the standard input stream.back_inserter(v[0])is an output iterator which, when dereferenced and assigned to, invokesv[0].push_back().