Hobbyist
Hobbyist

Reputation: 925

How do I create an std::map with multiple indices?

The following works:

std::map<std::string, Animal*> animalMap;

animalMap["KillerRabbit"] = new KillerRabit;

But what if I wanted to do this?

animalMap["KillerRabbit"]["White"] = new KillerRabit;

I have no idea what the 'official' name for the indices brackets are, knowing them would help immensely while Googling =p

Upvotes: 1

Views: 128

Answers (2)

stonemetal
stonemetal

Reputation: 6208

sftrabbit gives the canonical way to do it. If you don't want multiple map look ups per key you could also use std::pair as a map key.

Here is an example of doing it that way.

Upvotes: 1

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

What you are looking for is a map of maps:

std::map<std::string, std::map<std::string, Animal*>> animalMap;

Now each value stored in animalMap is itself a std::map. The key type for both the outer and inner maps are std::string.

The [...] syntax is the subscript operator. More specifically, though, you subscript a map with keys. Keys are mapped to values.

Upvotes: 4

Related Questions