The reason you are getting only one permutation is because there's no permutation lexicographically greater that the current state of array: [2, 2, 1]
. See the documentation of std::permutation
:
Transforms the range [first, last) into the next permutation from the
set of all permutations that are lexicographically ordered with
respect to operator< or comp. Returns true if such permutation exists,
otherwise transforms the range into the first permutation (as if by
std::sort(first, last)) and returns false.
Consider using std::vector
instead of C-array and sorting it before calculating all the permutations:
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::string s = "bba";
const int ss = s.size();
std::vector<int> ar;
ar.reserve(ss);
constexpr int offset = 'a' - 1;
for(int i=0; i<ss; i++) {
int tmp = int(s[i]) - offset;
ar.push_back(tmp);
}
std::sort(ar.begin(), ar.end());
do {
for(auto i: ar) std::cout << i;
std::cout << '\n';
} while(std::next_permutation(ar.begin(), ar.end()));
return 0;
}
This outputs:
122
212
221
Live example
Update: as it was pointed out by @Someprogrammerdude, please see: Why should I not #include <bits/stdc++.h>
Update 2: as it was pointed out by @Jarod42 consider using 'a' - 1
instead of magic-constant 96
.