如何在循环中将元素添加到空向量? [英] how do i add elements to an empty vector in a loop?

查看:114
本文介绍了如何在循环中将元素添加到空向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在循环内创建一个空向量,并希望在每次向该循环中读取某些内容时向该向量中添加一个元素。

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.

这篇关于如何在循环中将元素添加到空向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆