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>.

#include <iostream>

int main()
    std::string input="ABC";
    std::vector<std::string> perms;
    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"));

1 comment:

Chris said...

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

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