adding to map< string, <vector<string> >

One of the exercises in my book is
Define a map for which the key is the family’s last name and
the value is a vector of the children’s names. Write code to add new
families and to add new children to an existing family.

We haven't really covered maps whose values themselves are containers. Just wanted to check, do I have the right idea?:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
	std::map< std::string, std::vector<std::string> > families;

	// add new families
	families["Jones"];
	families["Smith"];
	families["Doe"];

	// add children
	families["Jones"].push_back( "Jane" );
	families["Jones"].push_back( "Jim" );

	families["Smith"].push_back( "Agent" );
	families["Smith"].push_back( "Sam" );

	families["Doe"].push_back( "Jane" );
	families["Doe"].push_back( "John" );
Looks good to me.

However, if you are using a modern compiler* which supports C++11 initializer lists, you can simplify your code a lot:

1
2
3
4
5
6
7
8
std::map< std::string, std::vector<std::string> > families {
    {"Jones", {"Jane", "Jim"}},
    {"Smith", {"Agent", "Same"}},
    {"Doe", {"Jane", "John"}}
};

// and to add
families["David"] = {"Goliath", "Junior", "Brenda"};


* MinGW/GCC 4.7+, and C++ compiler of upcoming Visual Studio 2013
Thanks. Yup I can use initializer lists, I just assumed they wanted us to do it that way.
Last edited on
Topic archived. No new replies allowed.