Search code examples
c++vectorpush-back

Push_back function for Class defined vector


I have a vector that takes in class values of a class called Bug which stores a mass and number of legs for each instance. I'm having trouble using the push_back function, and suspect it's just a syntax issue, but can't figure out exactly what I'm doing wrong. I am trying to add 3 more values into the end of the vector. Here is my partial code:

std::vector<Bug> bugs(5); //vector definition
bugs.push_back(3);

Solution

  • if you are trying to add 3 default constructed Bugs, you will need to call push_back 3 times:

    struct Bug{};  
    std::vector<Bug> bugs(5); //vector instantiation 
    bugs.push_back(Bug{});
    bugs.push_back(Bug{});
    bugs.push_back(Bug{});
    

    You can also use emplace_back(). It expects constructor arguments.
    In this case, no arguments:

    struct Bug{};  
    std::vector<Bug> bugs(5);
    bugs.emplace_back();
    bugs.emplace_back();
    bugs.emplace_back();
    

    Apart from using a loop, you can add N new elements using resize:

    bugs.resize(bugs.size()+n);