算法std中的next_permutation()似乎没有修改数组

时间:2014-04-13 22:31:19

标签: c++ c++11 std

我有以下程序使用函数next_permutation()和输出:

 8 int main ()
 9 {
10     int myints[] = {1, 2, 3};
11
12     cout << "Before : " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << endl;
13
14     do {
15         cout << "loop : ";
16         cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << endl;
17     } while ( next_permutation(myints, myints + 3) );
18
19     cout << "After : " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << endl;
20
21     return 0;
22 }

$ ./a.out
Before : 1 2 3
loop : 1 2 3
loop : 1 3 2
loop : 2 1 3
loop : 2 3 1
loop : 3 1 2
loop : 3 2 1
After : 1 2 3

我期待第19行输出&#34; 3 2 1&#34;根据next_permutation()(http://www.cplusplus.com/reference/algorithm/next_permutation/的描述,它有相同的样本程序),但可以看出输出是&#34; 1 2 3&#34;。有人可以帮我理解。

谢谢你, 艾哈迈德。

2 个答案:

答案 0 :(得分:2)

该功能正是您所链接的文档所说的应该执行的操作:

  

如果函数可以确定下一个更高的排列,它会重新排列元素并返回true如果那是不可能的(因为它已经是最大可能的排列),它会根据第一个排列重新排列元素(按升序排序)并返回false(重点是加)

这正是发生的事情:由于您的do / while循环刚刚结束,您确定std::next_permutation的调用已返回false。因此,您传递到最后一个调用的数组已按降序模式排列,从而无法生成下一个最高排列。这也是为什么你看到循环之后的打印输出中的第一个排列 - 文档说当调用返回false时,输入按升序排序。

答案 1 :(得分:0)

如果数组返回false,则

next_permutation对数组进行排序,因此这是预期的行为。这被描述为here on cppreference

希望这有帮助!