【问题标题】:Segmentation Fault while getting input from 2D vector从二维向量获取输入时出现分段错误
【发布时间】:2022-01-07 16:53:57
【问题描述】:

运行以下代码时出现分段错误。

int main()
{

    int R, C, val;
    cin>>R>>C;
    vector<vector<int>> a;
    for(int i = 0; i < R; i++)
    {
        for(int j = 0; j < C; j++)
        {
             cin>>val;
             a[i].push_back(val);
        }
    }

但是当我把它改成这个时,它似乎工作了。是什么原因?

int main()
{

    int R, C, val;
    cin>>R>>C;
    vector<vector<int>> a;
    for(int i = 0; i < R; i++)
    {
        vector<int>temp;
        for(int j = 0; j < C; j++)
        {
             cin>>val;
             temp.push_back(val);
        }
        a.push_back(temp);
    }

无论RC 的值是多少,我都会遇到同样的错误。

【问题讨论】:

  • 嗨,也许附加一个调试器,看看它在哪里出现了故障?

标签: c++ c++11 segmentation-fault


【解决方案1】:

你从来没有告诉过vector&lt;vector&lt;int&gt;&gt;的大小,你尝试访问a[i]

你必须调整向量的大小。

int main()
{

    int R, C;
    std::cin >> R >> C;
    std::vector<std::vector<int>> a(R, std::vector<int>(C));
    for(int i = 0; i < R; i++)
    {
        for(int j = 0; j < C; j++)
        {
             std::cin >> a[i][j]; //because we resize the vector, we can do this
        }
    }
}

【讨论】:

    猜你喜欢
    • 2013-10-29
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 2022-07-13
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2020-06-24
    相关资源
    最近更新 更多