矢量上的分割错误

segmentation fault on vector

本文关键字:分割 错误      更新时间:2023-10-16

我有一段代码,它使用DFS算法来解决Leetcode中的子集问题。问题说明如下。

给定一组不同的整数,S,返回所有可能的子集。

注意:子集中的元素必须按非降序排列。解决方案集不能包含重复的子集。

例如,如果S=[1,2,3],则解为:[[3],[1],[2],[1,3,[1,3],[2,3],[1,2],[1,2]

我的c++代码如下,问题是它输出"=====",但之后它说"分段错误"。我真的不明白这个分割错误。有人能告诉我代码的哪一部分错了吗?

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
class Solution
{
public:
    //Solution();
    //~Solution();
    std::vector< std::vector<int>  > subset(std::vector<int> S){
        sort(S.begin(), S.end());
        std::vector< std::vector<int> > res;
        std::vector<int> temp;
        res.push_back(temp);
        dfs(res, temp, S, 0);
        return res;
    }
private:
    void dfs(std::vector<std::vector<int> > res, std::vector<int> temp,     std::vector<int> S, int pos){
        for (int i = pos; i <= S.size()-1; i++)
        {
        temp.push_back(S[i]);
        res.push_back(temp);
        dfs(res, temp, S, i+1);
        temp.pop_back();                    /* code */
        }
    }
        /* data */
    };

std::vector<int> array(3);
array[0]=1; array[1]=2; array[2]=3;
std::vector<std::vector<int> > res;
Solution MySolution;
res=MySolution.subset(array);
cout<<"======="<<endl;
cout<<res[0][0]<<endl;
     return 0;
}

您传递的是向量的副本,而不是向量引用。

    std::vector< std::vector<int> > res;
    std::vector<int> temp;
    res.push_back(temp);
    dfs(res, temp, S, 0);

此代码创建一个vector<vector<int>> res;,向其推送一个空向量,然后调用一个在此范围内不更改任何状态的函数。最后,使用res[0][0]取消引用。res[0]给出了一个空向量,因此第二个[0]分段故障。

替换此功能定义:

void dfs(std::vector<std::vector<int>> res, std::vector<int> temp, std::vector<int> S, int pos){...}

有了这个:

void dfs(std::vector<std::vector<int>>& res, std::vector<int>& temp, const std::vector<int>& S, int pos){...}

dfs(res, temp, S, i+1);,几乎可以肯定是问题的根源。在最后一次迭代中,i+1 == S.size()导致分段故障。一个简单的解决方案是:

for (int i = pos; i <= S.size()-2; i++)