# What's wrong with STL rotate algorithm?

Printable View

• 12-09-2006
Mathsniper
What's wrong with STL rotate algorithm?
Code:

```#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() {         int i, m, n;         int *d;         cin >> m;         cin >> n;         d = new int[m];         for (i = 0; i < m; i++)                 cin >> d[i];                 vector<int> v(d, d+m);         for (vector<int>::size_type i = 0; i < v.size(); i++)                 cout << v.at(i) << " ";         cout << endl;         rotate(v.begin(), v.begin()+n, v.end());                 for (vector<int>::size_type i = 0; i < v.size(); i++)                 cout << v.at(i) << " ";         cout << endl;         delete []d; }```
The output shows
Code:

```debian:~# ./10039 10 12 4 5 7 1 2 4 2 3 9 7 4 5 7 1 2 4 2 3 9 7 7 1 2 4 2 3 9 7 0 135073 *** glibc detected *** free(): invalid next size (fast): 0x0804c038 *** Aborted```
What's matter about the error?
• 12-09-2006
Mathsniper
if I try to change rotate part to
Code:

```for (i = 0; i < n; i++)   rotate(v.begin(), v.begin()+1, v.end());```
It works fine. Can I do this action in 1 line?
• 12-09-2006
Mario F.
The problem derives from the input you are giving to n. Rotate signature is something like this:

Code:

`std::rotate(iterator begin, iterator middle, iterator end);`
What it does is to grab the element at middle and place it at the begin. Next middle + 1 is placed and being + 1, then next + 2 is placed at begin + 2, etc... All the way untill middle becomes equal to container.end(). At that time it stops.

Given a container with values 3, 4, 5, 6, 7, if I do rotate(begin(), begin() + 3, end()), the resulting container will become 6, 7, 3, 4, 5

By passing it a value bigger than the size of the container you are effectively accessing memory you don't own.

You don't need to change the rotate part, you just need to pay attention to what value you enter for n.
• 12-09-2006
anonytmouse
I think you can simulate a 'multiple rotate' by using n % m as the middle.