在C++中生成一组整数的排列.获取分段错误
Producing permutations of a set of integers in C++. Getting Segmentation Fault
我试图解决一个涉及产生一组数字的所有排列的问题。这个想法看起来很简单(下面的代码),但我不断遇到分段错误。谁能告诉我我做错了什么?
void permute(set<int>& s, vector<int>& v) {
if(s.empty()) {
// read the permutation in v.
return;
}
set<int>::iterator i;
for(i = s.begin(); i != s.end(); i++) {
int x = *i;
s.erase(i);
v.push_back(x);
permute(s, v);
v.pop_back();
s.insert(x);
}
}
要在C++中使用std::next_permutation
产生所有排列。这里的问题是您无法排列集合,因为排序是由键比较器运算符(在您的情况下为 less than 运算符)预设的。您可以做的是将值存储在非关联容器中,然后试一试。
#include <set>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;
void permut(std::set<int> const &inp, std::vector<int> &all_permutations)
{
vector<int> tmp(inp.size());
copy(inp.begin(), inp.end(), tmp.begin());
vector<int> all_permutations;
do
{
copy(tmp.begin(), tmp.end(), back_inserter(all_permutations));
} while (std::next_permutation(tmp.begin(), tmp.end()));
}
permute()
函数在迭代可变容器并进行更改时以递归方式调用自身。 这违反了迭代器有效性承诺。
你可以尝试一些基于std::next_permutation()的东西
我还没有深入探讨你可以从集合中得到的精确行为,但似乎很明显,你在 for 循环中做的事情足以使迭代器无效。我建议重新设计东西,以便你有两组,并完成一个(开始时是完整的),同时在另一个(开始时为空)中生成排列。
相关文章:
- 如何从一组具有从左到右优先级的整数值创建有序整数键?
- 编写所需的代码以创建动态一维整数数组
- 我如何将一组整数集变成C 中的3D矢量
- 给定一组正整数 <=k 及其 n 个子集,找到哪些子集对给出原始集合的并集
- 如何将字符串形式的日期 ( "Dec 25, 2012" ) 转换为一组整数 (12/25/12)?
- 最长的子序列,其元素构成一组递增的整数
- 如何查找具有一组整数的函数的'max absolute sum'
- 给定一个整数数组和一个数k,计算长度为k的每个子数组的最大值
- C++将一组整数变量映射到值的有效方法
- 在C++中生成一组整数的排列.获取分段错误
- 给定一组 12 个整数,如何递归生成所有可能的 4 组 3 个整数?C++
- 从另一组整数中有效地删除一组整数
- 按变量数组中的列将一组整数从文本文件读入
- 保存一组整数的最佳方法
- 计算一组关系的整数映射的更有效的算法
- 如何将一维整数数组从 QML 发送到C++
- 我需要标记一组匹配的整数,以便用分数进行数学检查
- 如何在C++中添加一组整数
- 将一组整数读取为C++中的字符串
- 如何在c++中创建一组非标准顺序的整数