Generate Permutations of Data Sequences
Learn to generate permutations of data sequences.
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.
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 avector
ofstring
objects and sort it with thesort()
algorithm.
int main() {vector<string> vs{ "dog", "cat", "velociraptor" };sort(vs.begin(), vs.end());...}
The next_permutation()
...