I am trying to make a simple program which basically reverse the sequence of the vector. In other words after the program is ran, x[0] should be equal to 5. The output which I am currently getting is 5234. The 1 goes missing somewhere. I did include the <vector> header. Thanks in advance.
int main()
{
vector<int> x(5);
x[0] = 1;
x[1] = 2;
x[2] = 3;
x[3] = 4;
x[4] = 5;
for(int z = 0; z < x.size()-1; z++)
{
int temp = x[x.size() - (1+z)];
x[x.size() - (1+z)] = x[z];
x[z] = temp;
}
for(int s = 0; s < x.size() - 1; s++)
{
cout << x[s] << endl;
}
return 0;
}
Take a step back a minute. What do you think this will do if I just put in swap (pseudo code)
This will not reverse your collection. Or rather it will, but will then reverse it back again leaving you where you started. Say your collection has 4 elements:
So your terminating condition is wrong, you should only swap halfway…