Swapping data between two vectors

Started by
2 comments, last by BitMaster 11 years, 5 months ago
I'm curios about swapping data between two vectors and what will happen in the following code.
Will the switch affect both vectors or just the one calling swap()?


std::vector<bool>::iterator i;
std::vector<bool>::iterator j;

j = b.begin();

for(i = a.begin();i != a.end();i++)
{
a.swap(i,j);
j++;
}
Advertisement
The std::vector::swap(vector) function swaps the data between two vectors. I don't know which function you're using that takes two iterators...? vector::assign takes two iterators, but it doesn't swap. Also, why are you looping? I'm having a hard time understanding your code.
If you want to swap manually, you shouldn't use vector::swap, but std::swap, like this:

std::swap(*i, *j);


But in this case, I think vector::swap is better.

a.swap(b);
I don't want to swap the entire content of the vectors just up to a certain point. Ex, if I got 50 elements in both vectors i might want to swap the first 25.

If you want to swap manually, you shouldn't use vector::swap, but std::swap, like this:

std::swap(*i, *j);


The above is the solution with one minor caveat. Pre-C++11 it was the intention to use swap via ADL (so that the specialized swap function can be placed in the namespace of the participating objects instead of inside std). But if you specify the std namespace like that ADL will not be used. There are two ways to solve this (again, pre-C++11):
1) place "using namespace std;" in the block where swap is used and make an unqualified call to swap (without the std:: ).
2) use boost::swap.

This topic is closed to new replies.

Advertisement