我正在尝试在循环内创建一个空向量,并且希望在每次将某些内容读入该循环时向该向量添加一个元素.
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;
}
但这给了我错误信息.
您需要使用 std::vector::push_back() 代替:
You need to use std::vector::push_back() instead:
while(cin >> x)
myVector.push_back(x);
// ^^^^^^^^^
而不是 std::vector::insert(),正如你在链接中看到的,它需要一个迭代器来指示你想要插入元素的位置.
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.
另外,作为 @Joel 评论了什么,您应该删除向量变量定义中的括号.
Also, as what @Joel has commented, you should remove the parentheses in your vector variable's definition.
std::vector<float> myVector;
和不是
std::vector<float> myVector();
通过执行后者,您会遇到 C++ 的最烦人的解析问题.
By doing the latter, you run into C++'s Most Vexing Parse problem.
这篇关于如何在循环中向空向量添加元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
读取输入文件,最快的方法?read input files, fastest way possible?(读取输入文件,最快的方法?)
在 C++ 中读取格式化输入的最简单方法?The easiest way to read formatted input in C++?(在 C++ 中读取格式化输入的最简单方法?)
从 .txt 文件读取到 C++ 中的二维数组Reading from .txt file into two dimensional array in c++(从 .txt 文件读取到 C++ 中的二维数组)
如何在 C++ 中模拟按键按下How to simulate a key press in C++(如何在 C++ 中模拟按键按下)
为什么在 cin.ignore() 之后没有 getline(cin, var) 读取Why doesn#39;t getline(cin, var) after cin.ignore() read the first character of the string?(为什么在 cin.ignore() 之后没有 getline(cin, var) 读取
scanf 格式输入的 cin 类比是什么?What is the cin analougus of scanf formatted input?(scanf 格式输入的 cin 类比是什么?)