Avoid making copies with vectors vectors

I want to have a vector of vectors of some type, for example:

vector<vector<MyStruct> > vecOfVec;

Then create the vector MyStruct and fill it.

vector<MyStruct> someStructs;
// Populate it with data

Then finally add someStructs to vecOfVec;

vecOfVec.push_back(someStructs);

What I want to do is to avoid calling the copy constructor when clicking on the vector. I know this can be achieved using a vector of pointers, but I would like to avoid this if possible.

One strategy that I was thinking about seems to work, but I don't know if I overdid this issue.

// Push back an empty vector
vecOfVec.push_back(vector<MyStruct>());

// Swap the empty with the filled vector (constant time)
vecOfVec.back().swap(someStructs);

It seems like it will add my vector without having to make any copies, but this is similar to what the compiler already did during the optimization.

Do you think this is a good strategy?

Edit: My swap operator is simplified due to some suggestions.

+3
5

, ++ 03. ++ 0x std::move, .

- vector<MyStruct>, , , a vector<MyStruct>& . vector<vector<MyStruct>> , .

+6

, , , .

?

// , , (, , ).

+4

,

. , boost:: shared_ptr.

. boost:: shared_ptr > . / ( , , ), . .

, .

using boost::shared_ptr;
vector<shared_ptr<vector<MyStruct> > vecOfVecs;
shared_ptr<vector<MyStruct> > someStructs(new vector<MyStruct>);
// fill in the vector MyStructs
MyStructs->push_back(some struct.... as you usually do).  
//...
vecOfVecs.push_back(someStructs); // Look! No copy!

boost:: shared_ptr, boost.org, . , ++.

+3

- vect.push_back (vector <MyStruct> ()); do vect.back(). push_back (MyStruct()); <MyStruct>

0

, - , :

vecOfVec.push_back(vector<MyStruct>());
vecOfVec.back().swap(someStructs);
0

Source: https://habr.com/ru/post/1725434/


All Articles