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
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.
One way to initialize a map is to copy contents from another map one after another by using the copy constructor.
Hi Naveen, *You can Create map of both String and Integer, just keep sure that your key is Unique.
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.
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" } }
};
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"))
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With