Modify a vector parameter

Write a function SwapVectorEnds() that swaps the first and last elements of its vector parameter. Ex: sortVector = {10, 20, 30, 40} becomes {40, 20, 30, 10}. The vector's size may differ from 4.

I keep getting 40 30 30 40 as output

1
2
3
4
5
6
7
  void SwapVectorEnds(vector<int>& sectorVector){ 
int i = 0;
for ( i = 0; i < sectorVector.size() - 1; ++i) {
  sectorVector.at(i) = sectorVector.at(sectorVector.size() - 1 - i);
}
   return;
}
closed account (ybf3AqkS)
1
2
3
4
5
6
void SwapVectorEnds(vector<int>& v)
{
    int t = v[0];
    v[0] = v[v.size()-1];
    v[v.size()-1] = t;
}
Thanks!!!!
You can condense the above answer by simply calling std::swap on front() and back()

std::swap(v.front(), v.back());
Last edited on
Topic archived. No new replies allowed.