将整数输入写入 C++ 中的向量容器
同样,我们在数组中
for (.....)
cin>>a[i];
如何使用向量来做到这一点。我声明了一个整数向量,
vector<int> v;
现在我需要从控制台获取输入并将其添加到向量中。我正在使用向量,因为我不知道限制。
likewise we do in array
for (.....)
cin>>a[i];
how we can do this using vectors. i declared a vector of integers
vector<int> v;
now i need to take inputs from console and add append those in vector.i am using vector because i donot know the limit.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
要从控制台将整数插入向量并打印出所有内容:
向量还提供了打印最大大小的功能:
To insert integer to a vector from console and print everything out:
And vector also provides you to print out the max size with:
如果向量未使用初始容量进行初始化,则使用如下所示的内容:
If the vector isn't initialized with an initial capacity, then use something like this:
稍微更紧凑的版本:
Slightly more compact versions:
试试这个
请参阅此处
您可以将其简化为创建向量并使用迭代器初始化它:
Try this
See here
You can simplify this to just creating the vector and initializing it with iterators:
最简单的解决方案是使用
istream_iterator
。你不想要 std::copy ,强硬,因为那是贪婪的。它会读取所有内容。相反,使用这个:The easiest solution is with an
istream_iterator
. You don't want std::copy, tough, because that's greedy. It will read everything. Instead, use this:通过 C++ 中的向量获取用户输入的小程序
Small program for taking input from user through vector in c++
当未给出输入数量时,我们将进行这样的编码
/在上面的代码中,我正在接受输入,直到用户未输入-1。在您的问题中,还必须给出一些条件而不是输入数量,并且如果给出输入的数量,那么就很容易接受输入。代码是:/
When number of inputs are not given then we to code like that
/In above code i am taking input till user has not entered -1.In your question also there must be some condition given instead of number of inputs and if the number of inputs are given then it's very easy to take input.The code for that is:/
您还可以动态分配数组,然后在向量中使用它。
这就是您可以做的,
这是您可以做的简单方法。
You can also dynamically allocate an array and then use it in a vector.
Here it is what you can do,
Its an Easy approach you can do.