-3

I have a vector of int's... I just want to swap two values.

    std::vector<int> vec;

    vec.push_back(0);
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);
    vec.push_back(4);
    vec.push_back(5);
    vec.push_back(6);
    vec.push_back(7);
    vec.push_back(8);

    std::swap(vec.begin(), vec.end());

Before the swap being called I have my vec as:

[0,1,2,3,4,5,6,7,8]

After the std::swap(...) I was hoping to have the vec as:

[8,1,2,3,4,5,6,7,0]

But it remains as the initial state. What is the problem here?

waas1919
  • 2,365
  • 7
  • 44
  • 76
  • 2
    You're looking for [`std::iter_swap`](http://en.cppreference.com/w/cpp/algorithm/iter_swap), that swaps the dereferenced values. You also can not give it `vec.end()` as an argument. – LogicStuff Dec 22 '15 at 21:43
  • 1
    Why does this even compile? `swap` requires lvalues as arguments, and `begin` and `end` yield rvalues. Is this MSVC with language extensions enabled? – dyp Dec 22 '15 at 21:44
  • 3
    @LogicStuff `iter_swap` won't help much if OP tries to use the `.end()` iterator – Piotr Skotnicki Dec 22 '15 at 21:44
  • @vsoftco I've tried it with clang++ and g++ with libc++ and libstdc++ and it **did not compile**: http://coliru.stacked-crooked.com/a/4bafc70816c9eba6 – dyp Dec 22 '15 at 21:58
  • @dyp I take it back, I was dereferencing them. It would have been extremely weird to compile indeed. Probably OP is using MSVC which allows rvalue binding to non-const ref. – vsoftco Dec 22 '15 at 21:58

1 Answers1

6

This should do the trick

assert(!vec.empty());
std::swap(vec.front(), vec.back());
Viktor Sehr
  • 12,825
  • 5
  • 58
  • 90