In this section, we will write a program that reads multiple word strings from a standard input, and then we will use std::next_permutation to generate and print all the permutations of those strings:
- First things first again; we include all the necessary headers and declare that we use the std namespace:
#include <iostream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
using namespace std;
- We begin with a vector of strings, which we feed with the whole standard input. The next step is sorting the vector:
int main()
{
vector<string> v {istream_iterator<string>{cin}, {}};
sort(begin(v), end(v));
- Now, we print the vector's content on the user terminal. Afterward, we call std::next_permutation. It systematically shuffles the vector to generate a permutation of its items, which we then print again. The next_permutation will return false as soon as the last permutation was reached:
do {
copy(begin(v), end(v),
ostream_iterator<string>{cout, ", "});
cout << 'n';
} while (next_permutation(begin(v), end(v)));
}
- Let's compile and run the function with some example input:
$ echo "a b c" | ./input_permutations
a, b, c,
a, c, b,
b, a, c,
b, c, a,
c, a, b,
c, b, a,