我需要对列表进行循环排列,例如我有:(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_permutation
和 prev_permutation
如果你不想做旋转以外的事情。
关于c++ - 具有两个迭代器的循环排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27532029/