Transfer ownership of STL containers?

Is it possible to transfer ownership of vector content from one vector to another?

vector<T> v1; 
// fill v1
vector<T> v2 = OvertakeContents(v1);
// now v1 would be empty and v2 would have all the contents of v1

It is possible to use lists with splicing function. This should be possible for a constant time for the whole vector.

If this is not so, why not?

+5
source share
3 answers

Check out std :: swap

vector<T> v1; 
// fill v1

vector<T> v2;

swap(v1, v2);
OR
v2.swap(v1);

Exchange certificate

+10
source

std :: vector has a swap () function that works something like this.

vector<T> v2;
v2.swap(v1);
+10
source

:

1) swap . , . , a.swap(b) . : , , swap , , . X, (X &, X &) X:: swap (X &). , X:: swap (X &) , . X ​​-, - , , .

2) if you need another container that has the same elements for which you want to transfer ownership Create a simple copy to increase efficiency

0
source

All Articles