Std::next_permutation缺少一个表项

std::next_permutation missing one entry

本文关键字:一个 next permutation Std      更新时间:2023-10-16

下面的程序缺少一个排列条目

#include <iostream>
#include <vector>
#include <algorithm>
int main ( int argc, char **argv) {
    std::vector<int> temp;
    temp.push_back(10);
    temp.push_back(2);
    temp.push_back(4);
    temp.push_back(4);
    do {
        std::copy(temp.begin(),temp.end(),std::ostream_iterator<int>(std::cout," "));
        std::cout << std::endl;
    }while ( std::next_permutation (temp.begin(), temp.end()));
}
下面是程序 的输出
10 2 4 4
10 4 2 4
10 4 4 2

为什么缺少一个条目

2 4 4 10

这是因为该排列是您所拥有的数字列表的第一个排序。您需要对原始数组进行排序,然后这个排列将被列为第一个。

std::vector<int> temp;
temp.push_back(10);
temp.push_back(2);
temp.push_back(4);
temp.push_back(4);
std::sort(temp.begin(),temp.end() );

或者,您可以按排序顺序推入元素,但出于实际目的,如果您希望生成所有可能的排列,则始终应该排序。

它实际上缺少一些其他有效的排列:例如2 10 4 42 4 10 4,和4 4 10 2

至于为什么它们不见了:它说,就在文档中:

返回值如果函数可以将对象重新排列为字典顺序上更大的排列,则为true。否则,函数返回false,表示排列不大于前一个,而是可能的最小排列(按升序排序)。

所以while循环在10 4 4 2之后结束,因为这是字典顺序上最大的排列(当你从左到右比较它们时,最大的一个,即按降序排列的那个)。在打印完这个之后,next_permutation不能到达"下一个"排列,而是绕到2 4 4 10的"开始"排列;但是它不会被打印出来,因为函数也返回false。