在C++中生成一组整数的排列.获取分段错误

Producing permutations of a set of integers in C++. Getting Segmentation Fault

本文关键字:整数 一组 排列 获取 错误 分段 C++      更新时间:2023-10-16

我试图解决一个涉及产生一组数字的所有排列的问题。这个想法看起来很简单(下面的代码),但我不断遇到分段错误。谁能告诉我我做错了什么?

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 循环中做的事情足以使迭代器无效。我建议重新设计东西,以便你有两组,并完成一个(开始时是完整的),同时在另一个(开始时为空)中生成排列。