c++ - 具有两个迭代器的循环排列

标签 c++ iterator iterator-traits

我需要对列表进行循环排列,例如我有:(a,b,c,d,e) 我想要 (e,a,b,c,d)。但是我没有成功,这里是我尝试过的:

#ifndef ALGORITHME_H
#define ALGORITHME_H

template<typename I>  
void permutationCirculaire(I first, I last) {
    typename std::iterator_traits<I>::value_type firstElement = *first;
    typename std::iterator_traits<I>::value_type res;
    I tmp = first;

    for (++first; tmp != last; ++tmp) {
        *first = *tmp;
        std::cout << "tmp : " << *tmp << ", first : " << *first << std::endl;
        ++first;
    }


}

#endif

我明白了: tmp : a, first : a tmp : a, first : a tmp : a, first : a tmp : a, first : a tmp : a, first : a

我不知道为什么,我的主要:

#include <iostream>
#include <list>
#include "algorithme.h"

using namespace std;

int main() {    
    list<char> liste;
    liste.push_back('a');
    liste.push_back('b');
    liste.push_back('c');
    liste.push_back('d');
    liste.push_back('e');

    cout << "( ";
    for (list<char>::iterator it = liste.begin(); it != liste.end(); ++it) {
        cout << *it << " ";
    }
    cout << ") " << endl;

    cout << "Permutation : " << endl;
    permutationCirculaire(liste.begin(),liste.end());

    cout << "( ";
    for (list<char>::iterator it = liste.begin(); it != liste.end(); ++it) {
        cout << *it << " ";
    }
    cout << ") " << endl;

    return 0; 
}

如果你知道为什么不要犹豫......

最佳答案

jaunchopanza 所述rotate是你应该使用的。

所以替换这个:

cout << ") " << endl;

cout << "Permutation : " << endl;
permutationCirculaire(liste.begin(),liste.end());

cout << "( ";

有了这个:

rotate(liste.begin(), advance(liste.begin(), liste.size() - 1), liste.end());

请注意,通过更改 advance 调用中的数字来调整旋转的字符数。
size() - 1 旋转

a, b, c, d, e

e, a, b, c, d

如果你使用 2 而不是 size() - 1 你会得到:

c, d, e, a, b

同时考虑:next_permutationprev_permutation如果你不想做旋转以外的事情。

关于c++ - 具有两个迭代器的循环排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27532029/

相关文章:

c++ - 明确禁止具体类模板特化

generics - 如何为任何元素序列实现特征?

c++ - 为什么在模板函数中使用 iterator_traits 而不是仅仅使用另一个模板类型参数?

rust - 编写具有适用于 Vec 和数组 [] 的特征的 Rust 函数

rust - 当忽略某些值时,如何避免迭代器实现中不必要的昂贵操作?

c++ - 从 C++ 中具有非常量数组大小的函数返回数组指针

c++ - 从 boost::asio::io_service 中删除所有处理程序而不调用它们

java - 如何使用 Iterator 从 Java 中的主列表中删除整个列表

boost - 使用 Boost Python 将 Python 列表输入到接受向量的函数中

C++11 访问具有限定名称的无作用域枚举数