Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add elements to an empty vector in a loop?

Tags:

c++

insert

vector

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.

like image 517
Amber Roxanna Avatar asked Aug 01 '13 02:08

Amber Roxanna


People also ask

How do you add elements to an empty vector in C++?

To insert an element in the vector, we can use vector::push_back() function, it inserts an element at the end of the vector. Syntax: vector_name. push_back(element);

How do you add values to a vector?

Adding elements in a vector in R programming – append() method. append() method in R programming is used to append the different types of integer values into a vector in the last. Return: Returns the new vector after appending given value.


1 Answers

You need to use std::vector::push_back() instead:

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.

Also, as what @Joel has commented, you should remove the parentheses in your vector variable's definition.

std::vector<float> myVector; 

and not

std::vector<float> myVector(); 

By doing the latter, you run into C++'s Most Vexing Parse problem.

like image 120
Mark Garcia Avatar answered Sep 23 '22 04:09

Mark Garcia