C++ trying to swap values in a vector

user782311 picture user782311 · Jun 3, 2011 · Viewed 154.5k times · Source

This is my swap function:

template <typename t>
void swap (t& x, t& y)
{
    t temp = x;
    x = y;
    y = temp;
    return;
}

And this is my function (on a side note v stores strings) call to swap values but whenever I try to call using values in a vector I get an error. I'm not sure what I'm doing wrong.

swap(v[position], v[nextposition]); //creates errors

Answer

Moha the almighty camel picture Moha the almighty camel · Nov 5, 2013

I think what you are looking for is iter_swap which you can find also in <algorithm>.
all you need to do is just pass two iterators each pointing at one of the elements you want to exchange.
since you have the position of the two elements, you can do something like this:

// assuming your vector is called v
iter_swap(v.begin() + position, v.begin() + next_position);
// position, next_position are the indices of the elements you want to swap