tags:

views:

201

answers:

3

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?

+10  A: 

Check out std::swap

vector<T> v1; 
// fill v1

vector<T> v2;

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

Swap Reference

RC
your note is completely false: all STL containers provide an equivalent overload of std::swap(a,b) with the same semantics as a.swap(b)
Greg Rogers
@Greg. Thanks for pointing out the error in my note. Upon looking at the reference for Vector.swap, they do indeed have the same semantics.
RC
+10  A: 

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

vector<T> v2;
v2.swap(v1);
Fred Larson
I almost upvoted you, however, your code is syntactically wrong.
avakar
@avakar: You're right. Corrected.
Fred Larson
A: 

Here there are two points:

1) For any Assignable type, swap can be defined in terms of assignment. This requires three assignments, each of which, for a container type, is linear in the container's size. In a sense, then, a.swap(b) is redundant. It exists solely for the sake of efficiency: for many containers, such as vector and list, it is possible to implement swap such that its run-time complexity is constant rather than linear. If this is possible for some container type X, then the template specialization swap(X&, X&) can simply be written in terms of X::swap(X&). The implication of this is that X::swap(X&) should only be defined if there exists such a constant-time implementation. Not every container class X need have such a member function, but if the member function exists at all then it is guaranteed to be amortized constant time.

2) if You need another container which has same elements for which you wanted to transfer ownership Please create a simple copy for better efficiency

sat