how do i add elements to an empty vector in a loop?

后端 未结 4 2184
[愿得一人]
[愿得一人] 2020-12-15 16:14

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 

        
相关标签:
4条回答
  • 2020-12-15 16:43

    Use push_back:

    while(cin >> x)
      myVector.push_back(x);
    

    The insert function takes an iterator as the first argument, indicating the position to insert.

    Also, you need to get rid of the parentheses in the declaration of myVector:

    std::vector<float> myVector;
    
    0 讨论(0)
  • 2020-12-15 16:45

    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.

    0 讨论(0)
  • 2020-12-15 16:47

    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.

    This is demonstrated in the std::vector::emplace_back documentation and here is a related question.

    Usage example:

    std::vector<int> myVector;
    
    while (cin >> x) {
        myVector.emplace_back(x);
    }
    
    0 讨论(0)
  • 2020-12-15 16:56

    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).

    0 讨论(0)
提交回复
热议问题