I need to make an circular permutation of an list for example I have : (a,b,c,d,e) I want (e,a,b,c,d). But I don't succeed to do so, here what I tried :
#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
I get this : tmp : a, first : a tmp : a, first : a tmp : a, first : a tmp : a, first : a tmp : a, first : a
And I don't know why, my main :
#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;
}
If you knwo why don't hesitate...
I finally succeed to correct my problem here is my solution, thanks everyone for your help :
template<typename I>
void permutationCirculaire(I first, I last) {
typename std::iterator_traits<I>::value_type current = *first;
typename std::iterator_traits<I>::value_type save = *(--last);
for(; first != last; ++first) {
current = *first;
*first = save;
save = current;
}
*first = save;
}
Sorry again for the mistakes.