Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...