2013-02-18 106 views
1

如果我有后不同的结果:next_permutation有被称为功能

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 ... abced5

这是我想

但是,如果我做:

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,看起来像是返回一个bool,所以我现在很困惑。

回答

10
bool shuffle(string & s){ 
        ^

因为您是通过值来传递字符串,所以不会修改传递的参数,所以您一次又一次地将相同的字符串传递给函数。

+0

很好的接收,非常感谢! – HoKy22 2013-02-18 20:35:12

3

next_permutation正在修改您的字符串以维持当前状态。使用中间函数shuffle可以修改原始字符串的副本。为了解决这个问题,试着定义这样的洗牌:

bool shuffle(string &s) 
+0

明白了,谢谢! – HoKy22 2013-02-18 20:36:04