[英]segmentation fault on vector
I have a piece of code which uses the DFS algorithm for solving the subset problem in Leetcode. 我有一段代码使用DFS算法解决Leetcode中的子集问题。 The problem is stated as below.
问题说明如下。
Given a set of distinct integers, S, return all possible subsets. 给定一组不同的整数S,返回所有可能的子集。
Note: Elements in a subset must be in non-descending order. 注意:子集中的元素必须为非降序排列。 The solution set must not contain duplicate subsets.
解决方案集不得包含重复的子集。
For example, If S = [1,2,3], a solution is: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] 例如,如果S = [1,2,3],则解决方案是:[[3],[1],[2],[1,2,3],[1,3],[2,3] ,[1,2],[]]
my c++ code is as below, the problem is that it outputs "=======", but after that it says "segmentation fault". 我的C ++代码如下,问题是它输出“ =======”,但之后却显示“分段错误”。 I don't really get this segmentation fault error.
我没有真正得到此细分错误错误。 Can someone tell me which part of the code is wrong?
有人可以告诉我代码的哪一部分错了吗?
#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;
}
You are passing copies of vectors, not vector references. 您正在传递矢量的副本,而不是矢量引用。
std::vector< std::vector<int> > res;
std::vector<int> temp;
res.push_back(temp);
dfs(res, temp, S, 0);
This code creates a vector<vector<int>> res;
这段代码创建了
vector<vector<int>> res;
, pushes an empty vector to it, then calls a function that does not change any state within this scope. ,将空向量推入该向量,然后调用一个不会更改此范围内任何状态的函数。 Finally, you then de-reference with
res[0][0]
. 最后,然后使用
res[0][0]
取消引用。 res[0]
gives an empty vector, so then the second [0]
segfaults. res[0]
给出一个空向量,因此第二个[0]
。
Replace this function definition: 替换此函数定义:
void dfs(std::vector<std::vector<int>> res, std::vector<int> temp, std::vector<int> S, int pos){...}
With this: 有了这个:
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);
, is almost certainly the source of your problem. ,几乎可以肯定是您问题的根源。 On the last iteration,
i+1 == S.size()
resulting in a segmentation fault. 在最后一次迭代中,
i+1 == S.size()
导致分段错误。 An easy fix is: 一个简单的解决方法是:
for (int i = pos; i <= S.size()-2; i++)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.