Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transfer ownership within STL containers?

Tags:

c++

stl

ownership

Is it possible to transfer ownership of a vector contents 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 for lists with splice function. This should be possible in constant time for whole vector as well.

If it isn't then why not?

like image 368
Łukasz Lew Avatar asked Sep 23 '09 13:09

Łukasz Lew


2 Answers

Check out std::swap

vector<T> v1; 
// fill v1

vector<T> v2;

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

Swap Reference

like image 113
RC. Avatar answered Oct 20 '22 00:10

RC.


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

vector<T> v2;
v2.swap(v1);
like image 41
Fred Larson Avatar answered Oct 19 '22 23:10

Fred Larson