我正在尝试一个示例程序,以了解prev和next排列之间的差异。然而,我的程序似乎无法正常工作。我通过询问数组中元素的数量来启动程序,并使用简单的for循环构建数组。
for(i = 0; i < x; i++)
ptr[i] = i;
cout << "Possible permuations using prev_permutation: " << endl;
do{
for(i = 0; i < x; i++)
cout << ptr[i] << " ";
cout << endl;
} while(prev_permutation(ptr, ptr+x));
cout << "Possible permuations using next_permutation: " << endl;
do{
for(i = 0; i < x; i++)
cout << ptr[i] << " ";
cout << endl;
} while(next_permutation(ptr, ptr+x));
当我用一个包含3个元素的样本(0、1、2)运行代码时,prev_permutation给了我(0, 1, 2),然后next_permutation给了我(2, 1, 0)。然而,当我注释掉prev_permutation部分的代码时,仅运行next_permutation就能获得集合(0、1、2)的6种不同排列。我似乎无法理解发生了什么。
(1 1 1 0 0)
是词典序中最后一个,因此您可以使用prev_permutations
从那里循环遍历所有排列。相反,第一个排列是(0 0 1 1 1)
,您可以使用next_permutation
从它开始循环遍历所有排列。 - 6502