Pranav Jituri Pranav Jituri - 3 months ago 10
C++ Question

Cannot determine why output is wrong while rotating vector

I have written the following code -

#include <cassert>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>

using namespace std;

vector<int> v;

int main()
{
int n, d, i = 0;
cin >> n >> d;
assert(n >= 1 && n <= 100000 && d >= 1 && d <= n);
int temp = 0;
for (int i = 0; i < n; i++)
{
cin >> temp;
v.push_back(temp);
}
reverse(v.begin(), v.begin() + d - 1);
reverse(v.begin() + d, v.end());
reverse(v.begin(), v.end());
for (i = 0; i < n; i++)
cout << v[i] << " ";
return 0;
}


Now, the problem is that when I enter the following input -

5 4
1 2 3 4 5


it doesn't give me the correct output
5 1 2 3 4
but rather gives me this
5 4 1 2 3


Any idea what might be wrong?

Answer

The output of the program is correct, for that input. It is your expectations that are incorrect.

The thing to realise is that standard algorithms do not dereference specified end iterators. So reverse(v.begin(), v.begin() + 3) will reverse the first three elements of v (i.e. v[0] through to v[2]) not the first four.

So the first reverse() reverses the first three elements, producing the order 3 2 1 4 5.

To get the results you expect, it would be reversing the first four.