C++ trying to swap values in a vector

C++VectorSwap

C++ Problem Overview


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

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

Both proposed possibilities (std::swap and std::iter_swap) work, they just have a slightly different syntax. Let's swap a vector's first and second element, v[0] and v[1].

We can swap based on the objects contents:

std::swap(v[0],v[1]);

Or swap based on the underlying iterator:

std::iter_swap(v.begin(),v.begin()+1);

Try it:

int main() {
  int arr[] = {1,2,3,4,5,6,7,8,9};
  std::vector<int> * v = new std::vector<int>(arr, arr + sizeof(arr) / sizeof(arr[0]));
  // put one of the above swap lines here
  // ..
  for (std::vector<int>::iterator i=v->begin(); i!=v->end(); i++)
    std::cout << *i << " ";
  std::cout << std::endl;
}

Both times you get the first two elements swapped:

2 1 3 4 5 6 7 8 9

Solution 3 - C++

There is a std::swap in <algorithm>

Solution 4 - C++

after passing the vector by reference

swap(vector[position],vector[otherPosition]);

will produce the expected result.

Solution 5 - C++

  1. Using std::swap by including the <algorithm> library to swap values by references / smart pointers,
    e.g. std::swap(v[0], v[1])
    Note: v[i] is a reference

  2. Using std::iter_swap from the same library,
    e.g. std::iter_swap(v.begin(), v.begin() + v.size() - 1)

  3. Using lvalue references and rvalue tuple by including the <tuple> library
    e.g. std::tie(v[0], v[1]) = std::make_tuple(v[1], v[0])
    Note: constexpr since C++14

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser782311View Question on Stackoverflow
Solution 1 - C++Moha the almighty camelView Answer on Stackoverflow
Solution 2 - C++linseView Answer on Stackoverflow
Solution 3 - C++Ólafur WaageView Answer on Stackoverflow
Solution 4 - C++faro_hfView Answer on Stackoverflow
Solution 5 - C++R.E.LView Answer on Stackoverflow