我有以下代码,我在其中定义了结构 vector 的 vector
#include <vector>
#include <iostream>
using namespace std;
struct node
{
int index;
double value;
};
int main()
{
vector < vector <node> >vett1;
node p;
p.index=5;
p.value=2;
for (int i=0; i<10; i++)
vett1[i].push_back(p);
return 0;
}
我不知道正确的填写方式。这样,当我运行它时,编译器会给我段错误。
最佳答案
当您访问 vett1[i]
时,但 vett1
尚未填充大小为零。这就是发生段错误的原因。
三种修复方式:
添加
vett1.resize(10);
在
for
循环之前。或者定义
vett1
并设置其大小如下:vector <vector <node>> vett1(10);
或者如果您事先不知道确切的尺寸,您可以这样做:
for (int i=0; i<10; i++) { vector<node> temp; temp.push_back(p); vett1.push_back(temp); }
关于c++ - 如何填充结构 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21241201/