Swapping values in vector

So this assignment asks us to swap the third value and the last value of a vector if the length of the vector is >=3. Somehow my code isn't working.

#include <iostream>
#include <vector>
using namespace std;

void swap3last(vector<int>& a)
{
if(a.size()>=3)
iter_swap(a.begin()+2, a.end());

}

Can someone help me with that
The std::vector.end() doesn't point to the last element. It points to one past the end of the vector.


I switched it to a.back(), it still doesn't work
the code does not work for any size, or only if size = 3?

if size = 3, then

a.begin ()+ 2 = a.end () ;

then do not swap..
I switched it to a.back(), it still doesn't work

What exactly isn't working?

The following seems to work for me.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <vector>
#include <iostream>

int main()
{
    std::vector<int> iv{3, 5, 7, 9, 12};
    if(iv.size() > 3)
        std::swap(iv[2], iv[iv.size() - 1]);

    for(auto& itr : iv)
        std::cout << itr << " ";

}


It gives me this error

void swap3last(vector<int>& a)
{
int i;
for(i=0;i<a.size();i++)
{if(a.size()>=3)
iter_swap(a.begin()+2, a.back());} //invalid type argument of unary β€˜*’ (have β€˜int’)//


}
never mind i got it. thanks jlb!
Topic archived. No new replies allowed.