如何在C ++中旋转向量中的第N个元素

罗希

我正在尝试旋转向量中的每个第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])
卡米尔库克

只需使用迭代器从初始向量创建具有指定最大长度的子范围,然后旋转每个子范围。

#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    

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章