为什么这个二维矢量会导致分段故障(磁芯转储)

Why this 2D vector cause the segment fault(core dumped)

本文关键字:分段 转储 故障 为什么 二维      更新时间:2023-10-16
#include <iostream>
#include <vector>
int main() 
{
    std::vector<std::vector<int>> a;
    a[0] = {1,2,3,4,5};
    a.push_back({12,123,123,1,3,1,23});
    size_t size = a.size();
    std::cout << size << std::endl;
}

g++编译器通过了这个程序,但是当我运行它时会出现此错误

分段故障(核心转储(

如何解决?如何计算此 2D 矢量中的所有元素?

在这里a[0] = { 1, 2, 3, 4, 5 };你在索引0处访问std::vector,但在索引0处没有std::vector,所以你访问了你不拥有的内存,这会导致分段错误!您必须首先分配空格(使用 resize (,或使用 push_back ,如下一行。

您可以在创建向量时分配第一行:

#include <iostream>
#include <vector>
int main()
{
    std::vector<std::vector<int>> a{{1,2,3,4,5}};
    a.push_back({12,123,123,1,3,1,23});
    size_t size = a.size();
    std::cout << size << std::endl;
}