[英]Segmentation Fault in vector<vector<string>>
Why am I getting segmentation fault in this piece of code?为什么我在这段代码中遇到分段错误?
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<vector<string> > v;
v[0].push_back("good");
cout<<v[0][0];
}
I am trying to insert the string "good" in the first vector, and I am trying to access that by v[0][0]
, but it is giving me segmentation fault
.我试图在第一个向量中插入字符串“good”,我试图通过v[0][0]
访问它,但它给了我segmentation fault
。 Please help.请帮忙。 Thanks.谢谢。
The inner vector starts out with 0 elements, you push 1 element and then you can access the first via [0]
.内部向量从 0 个元素开始,您推送 1 个元素,然后您可以通过[0]
访问第一个元素。 That's fine.没关系。
However, the outer vector works the same way: You first need to add an element before you can access it.但是,外部向量的工作方式相同:您首先需要添加一个元素才能访问它。
Either call the constructor that lets you specify the size:调用允许您指定大小的构造函数:
vector<vector<string> > v(1);
v[0].push_back("good");
or push the element:或推动元素:
vector<vector<string> > v;
vector<string> w;
w.push_back("good");
v.push_back(w);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.