Permutation combinations in Standard C++

Recently one of my colleagues and also another user in MSDN forum asked a question related to this. The question is as follows…

If I have a string vector with few elements like “Nibu” “Babu” “Thomas”, how can I get all combinations of these three strings? Results should look like…


So in C++ there is a standard C++ algorithm function called next_permutation. Use this function on an array of sorted strings to get required result. So some sample code follows…

[sourcecode language=”cpp”]
typedef std::string VT;
typedef std::vector< VT > VTVec;

// For dumping contents of vector to a stream
void Dump( VTVec& VecToPrint, std::ostream& stream )
// Get iterator for given stream, every element will be separated with second
// parameter.
std::ostream_iterator<VTVec::value_type> Itr( stream, ", " );
// Just one line to dump vector contents, no loops needed
std::copy( VecToPrint.begin(), VecToPrint.end(), Itr );

// Remove redundant space and bracket ( ", " ) from the end
stream << "bb  bbn";
}// End Dump

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
int nRetCode = 0;

VTVec vecNames;

std::sort(vecNames.begin(), vecNames.end());

std::cout << "nNames before applying permutations: ";
Dump(vecNames, std::cout);
std::cout << std::endl;

int Count = 0;
while(next_permutation(vecNames.begin(), vecNames.end()))
Dump(vecNames, std::cout);

std::cout << "nFound a total of " << Count << " combinations!n";
return nRetCode;

Result is as follows…

2 thoughts on “Permutation combinations in Standard C++

Appreciate your comments...