Friday, August 15, 2008

Permutations in C++

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]

1 comment:

Anonymous said...

For those playing at home, I got this working in Linux by adding:
#include <iterator>

And compiled with:
g++ -o permutations main.cpp