Std::next_permutation缺少一个表项
std::next_permutation missing one entry
下面的程序缺少一个排列条目
#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 4
和2 4 10 4
,和4 4 10 2
。
至于为什么它们不见了:它说,就在文档中:
返回值如果函数可以将对象重新排列为字典顺序上更大的排列,则为
true
。否则,函数返回false,表示排列不大于前一个,而是可能的最小排列(按升序排序)。
所以while
循环在10 4 4 2
之后结束,因为这是字典顺序上最大的排列(当你从左到右比较它们时,最大的一个,即按降序排列的那个)。在打印完这个之后,next_permutation不能到达"下一个"排列,而是绕到2 4 4 10
的"开始"排列;但是它不会被打印出来,因为函数也返回false。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 从链接列表c++中删除一个项目
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '