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. :)
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

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