i have a doubt on following case; suppose i want to define a vector of vector to acomadate set of elements and i can add the data and can be used those elemnts to compute something else. then i dont want that vector anymore. then later, suppose if i want to accomadae another set of data as a vector of vector, then i can reuse the previously created variable, then;
(1) if I created my vector of vector as dynamic memory and deleted as
vector<vector<double> > *myvector = new vector<vecctor<double> >;
//do push back and use it
delete myvector;
and then reuse again
(2) if I created my vector of vector as simply
vector<vector<double> > myvector;
//do push back and use it
myvector.clear();
and then reuse again
but, i guess in both method very few memory is remaining though we have removed it. so, i would like to know what is the efficient method to defin this vector of vector.
(3) if the size of the inside vector is always 2, then is it still efficient to use vector of vector by defining
vector<vect开发者_开发问答or<double> > myvector(my_list.size(), vector<double>(2))
other than another container type
(4) if i use predefined another class to hold inside 2 elements and then take a vector of those object type as (for example XY is the class which can hold 2 elements, may be as an array)
vector<XY>;
i hope, please anyone comment me what would be the most efficient method (from 1-4) interms of speed and memory needed. is there any better ways, plz suggest me too. thanks
If you only need two elements the most efficient way is probably:
std::vector<std::tr1::array<double, 2>> myvector;
// or std::vector<std::pair<double, double>> myvector;
// use it
myvector.clear(); // This will not deallocate any memory, so what has alrdy been allocated will be used for future push_backs
If this is homework (or not) and you want to know which is faster then you should try it: run the "push back and clear" or "new and delete" in a loop a few million times and time the execution. I suspect 2. will be a bit faster.
You say you want to accommodate a set of elements, and that the size of the inner vector is 2. That is a bit ambiguous, but you can further examine 2 things: 1. std::pair, if your "element" contains 2 other "things" 2. std::map, if you want to reference of of the "elements" based on the value of another "element"
精彩评论