C++ std算法中的next_permutation()似乎没有修改数组
我有以下使用函数next_permutation()的程序和输出:C++ std算法中的next_permutation()似乎没有修改数组,c++,c++11,std,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 cou
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
8 int main()
9 {
10整数myints[]={1,2,3};
11
12 coutnext\u permutation
如果数组返回false,则对数组进行排序,因此这是预期的行为。如下所述
希望这能有所帮助!该函数正是按照您链接的文档所说的那样执行的:
如果函数可以确定下一个更高的排列,它会重新排列元素,并返回true
如果这不可能(因为它已经是最大的可能排列),它会根据第一个排列(按升序排序)重新排列元素并返回false
(增加强调)
这正是正在发生的事情:由于您的do
/循环刚刚结束,您肯定知道std::next_permutation
的调用返回了false
。因此,您传递到最后一个调用中的数组已以降序模式排列,无法生成下一个highest排列。这也是为什么在循环之后的打印输出中会看到第一个排列-文档中说,当调用返回false
时,输入按升序排序。在原始代码的第11行,出现了以下语句“sort(myints,myints+3);”(我删除了它,程序的行为和我预期的一样)。我在其他示例程序中看到过类似的行。因为我是按升序创建数组的,所以确实需要sort()?