A small simple sample that illustrates how to get the various permutations of the characters of a string in C++ using std::next_permutation provided under the standard include <algorithm>.
[code]
#include<algorithm>
#include<string>
#include<vector>
#include <iostream>
int main()
{
std::string input="ABC";
std::vector<std::string> perms;
perms.push_back(input);
std::string::iterator itBegin = input.begin();
std::string::iterator itEnd = input.end();
while(std::next_permutation(itBegin, itEnd))
{
perms.push_back(std::string(itBegin, itEnd));
}
std::copy(perms.begin(), perms.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
}
[/code]
Friday, August 15, 2008
Permutations in C++
Posted by
abnegator
at
8/15/2008 10:04:00 PM
Labels:
algorithm,
C++,
next_permutation,
ostream_iterator,
permutations,
std::copy,
string,
vector
Subscribe to:
Post Comments (Atom)
1 comment:
For those playing at home, I got this working in Linux by adding:
#include <iterator>
And compiled with:
g++ -o permutations main.cpp
Post a Comment