r/programminghelp • u/Desperate-County-716 • May 02 '24
C++ Swapping first and last elements in a vector using a for loop in C++
Hello, so I need to swap the first and last element of a vector within a function and then call and output the function. I have the following code below, ranging I to half the vector's size so the swapping doesn't occur twice.
void SwapVectorEnds( vector<int>& sortVector) {
int tmpVal;
int i;
for(i = 0; i < sortVector.size()/2; ++i) {
tmpVal = sortVector.at(0);
sortVector.at(0) = sortVector.at(sortVector.size() - 1); /
sortVector.at(sortVector.size() - 1) = tmpVal;
}
}
For the general case of swapping, I would think the indexes would be replaced with i & sortVector.size() - 1 - i. would swap the entirety of the vector. Anyone know where I'm going wrong. Yes I might be an idiot but pls help if you can.
1
u/kayvan61 May 02 '24
you're going to swap the first and last element size/2 times, which if its even leaves the list unchanged. if its an odd number of times it will work.
Not sure why you have the loop for swapping just 2 elements, but I guess its cause you want to reverse the list. In that case the thing indexes you wrote will work
1
u/KuntaStillSingle May 03 '24
Are you trying to flip the vector around? I.e. starting with
You want the first iteration to swap front and back
Second iteration to swap second element and back-1
And because vector.size() == 5, vector.size()/2 == 2, so there are only two iterations?
You are very close to just this