C++ 二维 vector SIGSEGV 错误

标签 c++ vector segmentation-fault

我在下面的代码中遇到段错误,谁能解释一下。我认为这可能与初始化有关,但不确定。我只是想克隆现有堆栈并执行操作,例如向克隆添加条目或从现有堆栈中删除条目并将其克隆到新堆栈。

#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <deque>
#include <string>

using namespace std;

#define in cin
#define out cout

int main()
{
    //ifstream in("postfix.in");
    //ofstream out("postfix.out");

    int n;
    in>>n;

    long sum=0;
    vector<int> tm(0);
    vector<vector<int>> ar(0,tm);
    //ar[0].push_back(0);
    out<<ar[0][0];
    for(int i=0;i<n;i++)
    {
        int ind,val;
        in>>ind>>val;
        if(val==0)
        {
            for(int j=0;j<ar[ind-1].size();j++)
            ar[i].push_back(ar[ind-1][j]);
            ar[i].pop_back();
        }
        else
        {
            for(int j=0;j<ar[ind-1].size();j++)
            ar[i].push_back(ar[ind-1][j]);
            ar[i].push_back(val);
        }

    }

    for(int i=0;i<n;i++)
    {
        for(int j=0;j<ar[i].size();j++)
        sum+=ar[i][j];
    }

    out<<sum<<endl;

    return 0;

}

最佳答案

vector<int> tm(0);
vector<vector<int>> ar(0,tm);

在这里,您将 ar 初始化为 int vector 的 vector 。如果不通过push_back()resize()insert()等方式扩大其大小,则无法访问ar[i ]

您可以将 ar 初始化为

vector<vector<int>> ar(n);

但是在您提供的现有代码段中,没有关于第二个维度应该有多大的线索。

根据您在此答案中的评论,您对 tmar 的声明应该是

vector<int> tm(1, 0);
vector<vector<int>> ar(1, tm);

或者更短,因为 tm 以后并没有真正用到,

vector<vector<int>> ar(1, vector<int>(1, 0));

关于C++ 二维 vector SIGSEGV 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40551126/

相关文章:

java - 在 JNI 调用后尝试过快地访问数组时出现段错误

c++ - 抑制由于常量为零而导致比较始终为假的警告

c++ - 具有 void 函数的模板特化

java - 为什么当我使用变量时我的 vector 的大小更准确?

c++ - 在字符串的VECTOR中记录特定子串出现的次数

python - 树莓派上的“python”命令段错误

c - 当我提交代码时,IAM 在 codechef 中遇到 SIGSEGV 运行时错误

c++ - Qt Creator,C++,鼠标悬停功能

c++ - `unique_ptr::operator bool()` 是否为已从 move()d move 的 unique_ptr 定义?

algorithm - 点看点