矢量上的分割错误
segmentation fault on vector
我有一段代码,它使用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++)
相关文章:
- C++映射分割错误(核心转储)
- 由cin中的字符串中未捕获空白引起的分割错误
- 删除映射和分割错误中的一个过去结束元素
- 在指向函数中读取变量时出现分割错误
- 在链表中的第 n 位插入显示分割错误
- 较高值 n 的分割错误(例如 n=999997)
- 尝试通过memcpy复制大尺寸浮点向量时的分割错误
- 分割错误:向量中的擦除功能
- 向量向量的分割错误
- 我在C++中编写了一个方法来打印树类的预序,但它显示了分割错误
- C ++分割错误,为什么使用"long long"我没有得到答案?
- 在尝试使用递归查找集合子集的总数时,我遇到了分割错误
- 分割错误 11:尝试使用 cin 输入 B[1] 时
- 集合布局上的 Qt 分割错误
- 高达20亿的筛子会产生分割错误
- 对向量使用推回函数时的分割错误
- 绘制精灵会导致分割错误
- 将矢量的整数内容打印为字符串会导致分割错误
- 分割错误:使用向量时为 11 c++
- 结构的分割错误错误