Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing map<string, vector<string> >

I am initializing map<string, vector<string> > as follows:

map <string, vector<string> > dict;

dict["USA"].push_back("NYC");
dict["USA"].push_back("LA");
dict["USA"].push_back("Chicago");
dict["USA"].push_back("Dallas");

dict["India"].push_back("Delhi");
dict["India"].push_back("Bombay");

dict["Australia"].push_back("Melbourne");
dict["Australia"].push_back("Sydney");
dict["Australia"].push_back("Adelaide");

I find this cumbersome. The same thing can be done in tcl as follows which is cleaner:

array set dict {
USA {NYC LA Chicago Dallas}
India {Delhi Bombay}
Australia {Melbourne Sydney Adelaide}
}

Is there a more cleaner way to initialize in C++? My compiler is gcc 3.4.6

like image 588
Anand Avatar asked Mar 30 '12 21:03

Anand


People also ask

How do you put a string on a map of strings?

To insert the data in the map insert() function in the map is used. It is used to insert elements with a particular key in the map container. Parameters: It accepts a pair that consists of a key and element which is to be inserted into the map container but it only inserts the unique key.

Can we initialize map in C++?

One way to initialize a map is to copy contents from another map one after another by using the copy constructor.

Can we store string in map?

Hi Naveen, *You can Create map of both String and Integer, just keep sure that your key is Unique.

How do you map a vector?

Map of Vectors in STL: Map of Vectors can be very efficient in designing complex data structures. Syntax: map<key, vector<datatype>> map_of_vector; OR map<vector<datatype>, key> map_of_vector; For example: Consider a simple problem where we have to check if a vector is visited or not.


2 Answers

Initialization had many limitations in the old C++. Your code is in fact not initializing anything at all; it's just calling a lot of member functions on an already initialized object.

In the current C++ (C++11) you can initialize your map properly:

std::map<std::string, std::vector<std::string>> const dict {
   { "USA", { "NYC", "LA", "Chicago" } },
   { "India", { "Delhi", "Bombay" }    }
};
like image 163
Kerrek SB Avatar answered Sep 20 '22 14:09

Kerrek SB


If you're not opposed to using the Boost.Assign library and you are using C++ older than C++11, you can do it like this:

#include <boost/assign/list_of.hpp>
#include <boost/assign/std/vector.hpp>
#include <map>
#include <string>
#include <vector>

std::map<std::string, vector<std::string> > dict = boost::assign::map_list_of<std::string, std::vector<std::string> >
    ("USA",   boost::assign::list_of<std::string>("NYC")("LA")("Chicago")("Dallas"))
    ("India", boost::assign::list_of<std::string>("Delhi")("Bombay"))
;
like image 20
hatboyzero Avatar answered Sep 16 '22 14:09

hatboyzero