Take a look at the results of std::next_permuntation if you don't sort it:
#include <algorithm> #include <iostream> #include <iterator> #include <string> enum class sort { no, yes }; void show_permutations(std::string s, sort option) { if (sort::yes == option) { std::sort(std::begin(s), std::end(s)); } do { std::cout << s << '\n'; } while (std::next_permutation(std::begin(s), std::end(s))); } int main() { show_permutations("3412", sort::yes); std::cout << "Now without sorting...\n"; show_permutations("3412", sort::no); }
Examine the output to see if you notice anything interesting:
1234 1243 1324 1342 1423 1432 2134 2143 2314 2341 2413 2431 3124 3142 3214 3241 3412 3421 4123 4132 4213 4231 4312 4321 Now without sorting... 3412 3421 4123 4132 4213 4231 4312 4321
A sequence created without sorting is the same as the very end of a sequence created by sorting. What does this mean about the importance of entering an order?
What do you think will happen if you put the sort code inside a loop?
void show_permutations(std::string s, sort option) { do { if (sort::yes == option) { std::sort(std::begin(s), std::end(s)); } std::cout << s << '\n'; } while (std::next_permutation(std::begin(s), std::end(s))); }
Note that your program sorts the sides of the triangle inside the next_permutation loop, similar to this code, sorting the input line inside the loop.
source share