-2

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);
Cayden
  • 29
  • 5
  • @user1438832 what would the syntax be for this? Just replace push_back with emplace_back? – Cayden Jan 12 '17 at 05:55
  • 1
    `push_back()` adds only one element. If you want to add 3 more elements, either call `push_back()` 3 times or call `resize()` with the appropriate new size you want. – Cornstalks Jan 12 '17 at 05:56
  • 1
    @Cornstalks Thats exactly what I was looking for, I was unaware of the resize function. Thanks! – Cayden Jan 12 '17 at 05:58

1 Answers1

4

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);
ilent2
  • 5,171
  • 3
  • 21
  • 30
Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271