简体   繁体   English

为什么在C ++中输入数组时不能输入向量?

[英]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.

相关问题 我们可以在 c++ 中使用 vector 来获取未知大小的用户输入,直到我们按下 Enter 键吗? - Can we use vector in c++ to take user input of unknown size only till we hit enter? 我们可以在 C++ 中限制用户输入吗? - Can we limit user input in C++? 为什么我不能在C ++中输入我的std :: vector - Why I can't input into my std::vector in C++ 为什么我们在vs代码中写C++代码时不能通过一个变量来定义数组大小? - Why can't we define the array size by a variable when we write C++ code in vs code? 我们如何控制向量数组(c ++)中元素的内存分配? - can we control memory allocation for elements in the vector array (c++)? 为什么我们不能一步一步接受输入并进行操作? - Why can't we take input and manipulate it in one step? C++:为什么我们不能有对引用或引用数组的引用? - C++: why can't we have references to references or array of references? 为什么我们不能为C ++中的抽象类创建对象? - Why can't we create objects for an abstract class in C++? 当我们不知道输入的数量时,如何在 C++ 中读取空格分隔的输入 - How to read space separated input in C++ When we don't know the Number of input 我们可以将 integer 添加到 c++ 中的数组吗 - Can we add an integer to an array in c++
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM