C/C++ How to swap the first and last elements of a vector using a function in C++?

  • Thread starter Thread starter Teh
  • Start date Start date
  • Tags Tags
    Parameter Vector
Click For Summary
The discussion centers on a coding issue related to a function designed to swap the first and last elements of a vector. The initial implementation incorrectly loops through the entire vector, resulting in unexpected output. The suggested solution involves a more efficient approach: storing the last element in a temporary variable, assigning the first element's value to the last position, and then placing the stored value into the first position. This method simplifies the process and ensures the correct output, which should be {40, 20, 30, 10} when starting with {10, 20, 30, 40}.
Teh
Messages
47
Reaction score
0
What i am doing work because i can only get 40 30 30 40 as output?

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.
Code:
#include <iostream>
#include <vector>
using namespace std;

/* Your solution goes here  */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;
}
   
   
   
   
   
int main() {
   vector<int> sortVector(4);
   int i = 0;

   sortVector.at(0) = 10;
   sortVector.at(1) = 20;
   sortVector.at(2) = 30;
   sortVector.at(3) = 40;

   SwapVectorEnds(sortVector);

   for (i = 0; i < sortVector.size(); ++i) {
      cout << sortVector.at(i) << " ";
   }
   cout << endl;

   return 0;
}
Testing with original sortVector = {10, 20, 30, 40}



Expected output:
40 20 30 10



Your output:
40 30 30 40
 
Technology news on Phys.org
You are looping over the entire vector, which isn't necessary. What I would do is first store the last element in a variable, put the first element's value into the last element, and then put the value of the variable we stored the last element's initial value into the first element. :)
 
Anthropic announced that an inflection point has been reached where the LLM tools are good enough to help or hinder cybersecurity folks. In the most recent case in September 2025, state hackers used Claude in Agentic mode to break into 30+ high-profile companies, of which 17 or so were actually breached before Anthropic shut it down. They mentioned that Clause hallucinated and told the hackers it was more successful than it was...

Similar threads

  • · Replies 15 ·
Replies
15
Views
4K
  • · Replies 1 ·
Replies
1
Views
1K
Replies
20
Views
2K
  • · Replies 22 ·
Replies
22
Views
3K
  • · Replies 8 ·
Replies
8
Views
9K
  • · Replies 5 ·
Replies
5
Views
3K
Replies
1
Views
4K
  • · Replies 3 ·
Replies
3
Views
5K
Replies
12
Views
3K
  • · Replies 10 ·
Replies
10
Views
2K