Frage zu next_permutation
-
Hallo, ich versuche schon seit mehreren Stunden eine Funktion zu schreiben, die alle Elemente eine Vektors permutiert:
Ich habe folgendes Programmfragment gefunden, das auch funktioniert:
int main()
{
char v[] ="abcd";
cout<<v<<'\t';
while(next_permutation(v,v+4)) cout<<v<<'\t';
}führt zu:
abcd abdc acbd acdb adbc adcb bacd badc bcad bcda bdac bdca cabd cadb cbad cbda cdab cdba dabc dacb dbac dbca dcab dcba
Nun möchte ich aber kein char- Feld benutzen, sondern einen Vektor:
zum Beispiel: std::vector<char> v;
Wie würde dann das Programm aussehen?
Kann mir jemand helfen?
-
while(next_permutation(v.begin(),v.end())) cout<<v<<'\t';
-
Musst eben auch die Ausgabe anpassen -->
do { copy(v.begin(), v.end(), ostream_iterator<char>(cout)); cout << endl; } while(next_permutation(v.begin(),v.begin()+4));
-
vielleicht hilft es dir ja:
-
Hallo nochmal,
vielen Dank für die schnellen Antworten.
Das Programm:#include <iostream>
#include <vector>
#include <iterator>using namespace std;
int main()
{std::vector<char> v;
v.push_back('a');
v.push_back('b');
v.push_back('c');
v.push_back('d');do
{
copy(v.begin(), v.end(), ostream_iterator<char>(cout));
cout << endl;
} while(next_permutation(v.begin(),v.begin()+4));cout<<endl;
}funktioniert :-))
-
Ich finde es so schöner:
#include <iostream> #include <algorithm> #include <string> using namespace std; int main() { string str("abcd"); do cout << str << '\t'; while(next_permutation(str.begin(),str.end())); }