我正在尝试旋转向量中的第n个元素。我知道C ++中有一个rotate函数,但是如何旋转第n个元素?
例如:
([71 65 74 88 63 100 45 35 67 11])-->[65 74 88 71 100 45 35 63 11 67]
对于上面的示例,如果n = 4,则应该在第4个元素处进行旋转。
1st-->([71 65 74 88])-->([65 74 88 71])
2nd-->([63 100 45 35])-->([100 45 35 63])
3rd-->([67 11])-->([11 67])
答案 0 :(得分:5)
只需使用迭代器从初始向量创建具有指定最大长度的子范围,然后旋转每个子范围即可。
#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;
}
将输出:
65 74 88 71 100 45 35 63 11 67
答案 1 :(得分:1)
我的原始答案的简化版本。旋转是否到位?
void RoateEveryNth(vector<int>& vec, size_t n)
{
if (n <= 1)
{
return;
}
size_t numChunks = vec.size() / n;
size_t lastChunkSize = vec.size() % n;
for (size_t chunk = 0; chunk < numChunks; chunk++)
{
size_t offset = chunk * n;
int firstChunkValue = vec[chunk*n];
for (size_t i = 1; i < n; i++)
{
vec[offset + i - 1] = vec[offset + i];
}
vec[offset + n - 1] = firstChunkValue;
}
if (lastChunkSize > 1)
{
size_t offset = numChunks * n;
int firstChunkValue = vec[offset];
for (size_t i = 1; i < lastChunkSize; i++)
{
vec[offset + i - 1] = vec[offset + i];
}
vec[offset + lastChunkSize - 1] = firstChunkValue;
}
}
int main()
{
std::vector<int> vec = { 71, 65, 74, 88, 63, 100, 45, 35, 67, 11 };
RoateEveryNth(vec, 4);
for (int i : vec)
{
cout << " " << i;
}
cout << endl;
return 0;
}