[英]Two dimensional vector of integer C++. What's wrong?
I have trouble with two dimensional vector. 我在二维向量方面遇到麻烦。 Example: 例:
vector < vector<int> > data;
int i = 0;
int int_value;
while (i < 10 )
{
cin >> int_value;
data[i].push_back (int_value);
}
I want using push_back for back insert and then I want use data [i][j]. 我想将push_back用于后插入,然后要使用数据[i] [j]。 Where is the problem? 问题出在哪儿?
You need to initialize vector data
before using data[i]
. 您需要在使用data[i]
之前初始化矢量data
。 Otherwise, the vector is empty and accessing data[i]
is out of range. 否则,向量为空,并且访问data[i]
超出范围。 Also, you need to increment i
inside the while
loop: 另外,您需要在while
循环内增加i
:
vector < vector<int> > data(10); // creates a vector of size 10,
// each element being an empty vector of int's
int int_value;
for (int i=0; i < 10; i++)
{
cin >> int_value;
data[i].push_back (int_value); // add int_value to the ith vector
}
After the loop, each vector contains one int
value entered by the user. 循环之后,每个向量都包含一个由用户输入的int
值。
data[i]
does not exist, because the empty constructor of vector creates a vector of size 0. So when you call data[i]
this will be out of bounds. data[i]
不存在,因为vector的空构造函数创建了一个大小为0的向量。因此,当您调用data[i]
它将超出范围。 Just like a one dimensional vector first allocate enough elements for data. 就像一维向量首先为数据分配足够的元素一样。 In your case it seems you need to have data of size 10: 在您的情况下,您似乎需要具有大小为10的数据:
vector < vector<int> > data(10);
Also you never increase i
in the while loop which it seems will lead to infinite loop. 而且,您永远不会在while循环中增加i
,这似乎会导致无限循环。
You have an empty vector of vectors, and you are trying to access its elements ( data[i]
). 您有一个空的vector向量,并且您正在尝试访问其元素( data[i]
)。 Obviously, you can't do that before you add some (via push_back
, resize
or some other method of data
itself). 显然,您不能在添加一些内容之前做到这一点(通过push_back
, resize
或data
本身的其他方法)。
The problem is that data[i]
does not exist. 问题是data[i]
不存在。 First you need to push a vector<int>
into the vector< vector<int> >
vector, then you can add integers to it. 首先,您需要将vector<int>
推入vector< vector<int> >
vector,然后可以向其中添加整数。
vector < vector<int> > data;
data
is an empty vector which holds vector<int>
. data
是一个空的向量,其中包含vector<int>
。
data[i].push_back (int_value);
data
is empty. data
为空。 So, doing data[i]
leads to undefined behavior. 因此,执行data[i]
会导致未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.