How do I declare a vector of vector<Animal> ?

Hi experts,

   I have a struct

typedef struct{
  // blah
}Animal ;

and I need several different Animal vectors ...
i.e.  vector<Animal> Dog, Cat, Pig ;

but I want Dog, Cat, Pig to be stored as element of a new vector ?

How do I declare and use such a vector ???

 many thanks !
LVL 1
meow00Asked:
Who is Participating?
 
DarrylshConnect With a Mentor Commented:
Expanding on my last answer:
struct animal
{
...
};
vector <animal> dogs;
vector <animal> cats;
vector <animal> pigs;

vector <vector<animal> > AllAnimals;

AllAnimals.push_back(dogs);
AllAnimals.push_back(cats);
AllAnimals.push_back(pigs);
0
 
andrewjbConnect With a Mentor Commented:
Don't think it'll be very effficient - you'll be copying vectors around if you're not careful. But, just:

typedef struct ... Animal
typedef vector<Animal> uVecAnimal
typedef vector<uVecAnimal> uDblVecAnimal

uDblVecAnimal X;
0
 
jkrConnect With a Mentor Commented:
Are you thinking about something like

#include <vector>
#include <map>
using namespace std;

struct Animal {

    enum Race {

        Unknown,
        Dog,
        Cat,
        Pig
    };

    virtual Race GetRace () const = 0;

    //...

};

struct Dog : public Animal {

    virtual Race GetRace () const { return Dog};

    // ...

};

class Farm {

public:

    void AddAnimal ( Animal& a) {

        Animal::Race r = a.GetRace();
        map<Animal::Race,vector<Animal> >::iterator i = m_mapAnimal2Vector.find(r);

        if ( i == m_mapAnimal2Vector.end()) {

            vector<Animal> v;

            v.push_back(a);

            m_mapAnimal2Vector.insert(map<Animal::Race,vector<Animal> >::value_type(a,v));

        } else {

            i->push_back(a);
        }
    }

    vector<Animal>* GetAnimals ( Animal::Race r) {

        map<Animal::Race,vector<Animal> >::iterator i = m_mapAnimal2Vector.find(r);

        if ( i != m_mapAnimal2Vector.end()) {

            return i;
        }

        return NULL;
    }

protected:

    map<Animal::Race,vector<Animal> > m_mapAnimal2Vector;
};

?
0
 
DarrylshCommented:
vector<vector<Animal> >

note there MUST be a space between the last two "> >" or the compiler will interpret it as the shift operator >>
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.