Skip to main content
GameDev.net gamedev.net
🔒 Locked

Swapping data between two vectors

Started by Psilobe Oct 25, 2012 at 8:23 AM 2 replies 1.4k views
Original Post
Psilobe
Psilobe
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++;
}
patrrr
patrrr
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);
Psilobe
Psilobe
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.
BitMaster
BitMaster

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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.