为什么这个二维矢量会导致分段故障(磁芯转储)
Why this 2D vector cause the segment fault(core dumped)
#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;
}
相关文章:
- 分段故障(堆芯转储)矢量
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 分段错误(核心转储)但无法弄清楚
- 分段错误(核心转储) - 使用 SavedModel 的 Tensorflow C++ API 进行推断
- C++指针无法在函数外部传递值和分段错误(核心转储)错误
- 合并排序:分段错误核心转储
- C++:分段错误(核心转储)
- 分段错误(内核转储) C++面向对象编程
- 从 pybind11 构建导入模块时出现"分段错误(核心转储)"
- qt C++命令行代码中的分段错误(核心转储)
- C++ atof - 分段错误(核心转储)
- 为什么我的代码包含错误分段错误(核心转储)?
- 运行编译的 a.out 后出现分段错误(核心转储)错误
- 为什么我的代码给我一个分段/核心转储错误?
- 有关矩阵的代码错误导致分段错误(内核转储)
- 运行我的代码时出现分段错误(核心转储)问题
- C++代码的分段错误(核心转储)
- 分段故障(核心转储)-不知道为什么
- 为什么在使用字符指针 str1 而不是 str 时会出现分段转储?