1

如果我有:

bool shuffle(string s){
    return next_permutation(s.begin(), s.end());
}

int main(int argc, char* argv[]){    
        string m = "abcde5";
    do {
        cout << m << endl;
    } while(shuffle(m));

我会得到:

abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 abcde5 ...

不是我想要的

但是,如果我这样做:

int main(int argc, char* argv[]){    
string m = "abcde5";
do {
    cout << m << endl;
} while(next_permutation(m.begin(), m.end()));  

我会得到

abcde5 abce5d abced5 abd5ce abd5ec abdc5e abdce5 abde5c abdec5 abe5cd abe5dc abec5d abecd5 abed5c abedc5 ac5bde ac5bed ac5dbe ac5deb ac5ebd ac5edb acb5de acb5ed acbd5e acbde5 ... edcba5

这就是我想要的。

有什么不同?我查找了 next_permutation,看起来它返回一个布尔值,所以我现在真的很困惑。

4

2 回答 2

10
bool shuffle(string & s){
                    ^

You're passing the same string to the function over and over, because you're taking the string by value, and so not modifying the passed argument.

于 2013-02-18T20:33:31.293 回答
3

next_permutation is modifying your string to mantain the current state. With your intermediate function shuffle you modify a copy of the original string. To solve the problem try to define shuffle like this:

bool shuffle(string &s)
于 2013-02-18T20:34:42.310 回答