Home > Software engineering >  How to setup/fill a vector of structures c
How to setup/fill a vector of structures c

Time:09-16

I have a struct and some elements in it, I am trying to create a vector of structs and fill it up but tbh im pulling my hair out cause I have no idea what I am doing. Could someone please help me with how I should set this up?

'''

#include <iostream>
#include <string>
#include <vector>

using namespace std;

//define structs
struct animalS
{
    string animalType = "none";
    int animalCount = 0;
    bool animalEndangered = false;
};

int main()
{
    vector<animalS> animal;

    animal.push_back("" , 0 , true);
    
}

'''

enter image description here

CodePudding user response:

You have two mistakes, first one your animalS struct doesn't have a constructor, you should add constructor like this:

animalS(const std::string &animalType, int animalCount, bool animalEndangered)
  : animalType(animalType)
  , animalCount(animalCount)
  , animalEndangered(animalEndangered)
  {}

And use push_back() like this: animal.push_back(animalS("" , 0 , true))

  • Related