C++ 如何在循环中向空向量添加元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17984268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how do i add elements to an empty vector in a loop?
提问by Amber Roxanna
I am trying to create an empty vector inside a loop and want to add an element to the vector each time something is read in to that loop.
我正在尝试在循环内创建一个空向量,并希望在每次将某些内容读入该循环时向该向量添加一个元素。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
std::vector<float> myVector();
float x;
while(cin >> x)
myVector.insert(x);
return 0;
}
but this is giving me error messages.
但这给了我错误信息。
回答by Mark Garcia
You need to use std::vector::push_back()
instead:
您需要std::vector::push_back()
改用:
while(cin >> x)
myVector.push_back(x);
// ^^^^^^^^^
and not std::vector::insert()
, which, as you can see in the link, needs an iterator to indicate the position where you want to insert the element.
而 not std::vector::insert()
,正如您在链接中看到的那样,它需要一个迭代器来指示要插入元素的位置。
Also, as what @Joel has commented, you should remove the parentheses in your vector variable's definition.
此外,正如@Joel 所评论的那样,您应该删除向量变量定义中的括号。
std::vector<float> myVector;
and not
而不是
std::vector<float> myVector();
By doing the latter, you run into C++'s Most Vexing Parseproblem.
通过执行后者,您会遇到 C++最烦人的解析问题。
回答by Yang
Use push_back
:
使用push_back
:
while(cin >> x)
myVector.push_back(x);
The insert
function takes an iterator as the first argument, indicating the position to insert.
该insert
函数将迭代器作为第一个参数,指示要插入的位置。
Also, you need to get rid of the parentheses in the declaration of myVector
:
此外,您需要去掉以下声明中的括号myVector
:
std::vector<float> myVector;
回答by Nikunj
If you want to use myVector.insert()
,
use it like myVector.insert(myVector.end(), x)
. This will append x at the end of myVector.
You can insert x in the beginning by myVector.insert(myVector.begin(), x)
.
如果你想使用myVector.insert()
,就像使用它一样myVector.insert(myVector.end(), x)
。这将在 myVector 的末尾附加 x。您可以在开头插入 x myVector.insert(myVector.begin(), x)
。
回答by J-Alex
Another option is to use std::vector::emplace_back()
instead of std::vector::push_back()
. The makes some optimizations and doesn't take an argument of type vector::value_type
, it takes variadic arguments that are forwarded to the constructor of the appended item, while push_back
can make unnecessary copies or movements.
另一种选择是使用std::vector::emplace_back()
而不是std::vector::push_back()
. 进行了一些优化并且不接受 type 参数vector::value_type
,它接受传递给附加项的构造函数的可变参数,同时push_back
可以进行不必要的复制或移动。
This is demonstrated in the std::vector::emplace_backdocumentation and hereis a related question.
这在std::vector::emplace_back文档中得到了证明,这里有一个相关的问题。
Usage example:
用法示例:
std::vector<int> myVector;
while (cin >> x) {
myVector.emplace_back(x);
}