[英]Why can't we input a vector as we input an array in C++?
The wiki says: 维基说:
The elements of a vector are stored contiguously. 向量的元素是连续存储的。 AND
和
Vectors allow random access; 向量允许随机访问; that is, an element of a vector may be referenced in the same manner as elements of arrays (by array indices).
也就是说,可以以与数组元素相同的方式(通过数组索引)引用向量的元素。
So why can't we input the elements of a vector as: 那么为什么我们不能将向量的元素输入为:
vector<int> v;
for(int i=0;i<3;i++)
{
cin>>v[i];
}
Either you need to resize the vector upfront - as other answers say - or you can use C++ standard library. 就像其他答案所说的那样,您需要预先调整矢量的大小,或者可以使用C ++标准库。 Then the equivalent of your
for
loop is the following one line: 那么相当于
for
循环的是以下一行:
copy_n(istream_iterator<int>(cin), 3, back_inserter(v));
and it takes care of allocation/resizing. 并负责分配/调整大小。
The problem is that you need to allocate the elements of the vector first. 问题是您需要首先分配向量的元素。 So try
vector<int> v(4);
因此,尝试使用
vector<int> v(4);
, so it will start with 4 elements. ,因此将从4个元素开始。 Then you can load values into them.
然后,您可以将值加载到它们中。
Your vector has zero elements right now. 您的向量现在有零个元素。 Try allocating it some space as:
尝试为它分配一些空间,例如:
vector<int> v(5);
Then your method would work. 然后您的方法将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.