Search⌘ K
AI Features

Generate Permutations of Data Sequences

Explore how to generate permutations of data sequences using C++ STL's next_permutation function. Understand the importance of sorting containers first, the concept of lexicographical order, and handle cases with repeating values. This lesson equips you to produce and iterate through all lexical permutations in modern C++ code.

We'll cover the following...

There are many use cases for permutations, including testing, statistics, research, and more. The next_permutation() algorithm generates permutations by re-ordering a container to the next lexicographical permutation. permutation

How to do it

For this recipe, we will print out the permutations of a set of three strings:

  • We'll start by creating a short function for printing the contents of a container:

void printc(const auto& c, string_view s = "") {
if(s.size()) cout << format("{}: ", s);
for(auto e : c) cout << format("{} ", e);
cout << '\n';
}

We'll use this simple function to print our data set and permutations.

  • In the main() function, we declare a vector of string objects and sort it with the sort() algorithm.

int main() {
vector<string> vs{ "dog", "cat", "velociraptor" };
sort(vs.begin(), vs.end());
...
}

The next_permutation() function requires a sorted container. ...