I'm trying to rotate every nth element in a vector. I know there is a rotate function in c++ but how can i rotate every nth element?
For example:
([71 65 74 88 63 100 45 35 67 11])-->[65 74 88 71 100 45 35 63 11 67]
For the above example, if n=4 then rotation should happen at every 4th element.
1st-->([71 65 74 88])-->([65 74 88 71])
2nd-->([63 100 45 35])-->([100 45 35 63])
3rd-->([67 11])-->([11 67])
Just create subranges with specified maximum length from the initial vector using iterators and rotate each one of them.
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
template <class ForwardIterator>
void myrotate_nth (ForwardIterator first, ForwardIterator last,
typename std::iterator_traits<ForwardIterator>::difference_type n)
{
while (last - first > n) {
ForwardIterator tmp = first + n;
rotate(first, first + 1, tmp);
first = tmp;
}
rotate(first, first + 1, last);
}
int main()
{
std::vector<int> v = { 71, 65, 74, 88, 63, 100, 45, 35, 67, 11 };
myrotate_nth(v.begin(), v.end(), 4);
for_each(v.begin(), v.end(), [](int c) { cout << c << "\t"; });
cout << endl;
return 0;
}
Will output:
65 74 88 71 100 45 35 63 11 67
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With