Reputation: 13
current code
std::map<std::string,int> m;
...
m.insert(std::pair<std::string,int>(text,lineno));
...
std::cout<<"key: "<<iter->first<<"lineno: "<<iter->second<<std::endl;
how to save mutiple values in same key?
Upvotes: 0
Views: 2472
Reputation: 2950
std::map<std::string,int> m;
By declaring this (the above) you have instantiated map which the keys of this map
(m) of type string
and the values are of type int
.
In C++
you can declare a map
with keys and values pairs, from any type, what ever you like/need, so the answer would be, vector
or depends on what do you want to achieve from this Data Structure
.
here is ilustration with vector:
std::map<std::string,std::vector<int>> my_map;
here is ilustration with values of type map:
std::map<std::string, std::map<std::string, int>> my_map;
Note
If you are working with c++
version or standard compiler less that c++11
, you need to add space between the adjacent right angle brackets, like so:
std::map<std::string, std::map<std::string, int> > my_map;
Upvotes: 2
Reputation: 369
To sum up the comments of others, here's an answer.
Say you have some type T
and would like to map a std::string
to multiple values of that type. The easiest way to do this, when you don't know how many multiple values you need to map to, is to use an std::vector <T>
. If you do know how many multiple values you're going to be dealing with for each key, you could map to an std::array <T>
.
std::map <std::string, std::vector <int>> map;
map ["A"].push_back(10);
map ["B"].push_back(20);
map ["A"].push_back(42);
You could use a std::multimap <std::string, int>
similarly if you're dealing with what I showed above.
std::multimap <std::string, int> map;
map.insert({"A", 10});
map.insert({"B", 20});
map.insert({"A", 42});
If you would like to map one key to multiple values that are to hold information of different types, you could use a std::map <std::string, std::vector <std::tuple <int, std::string, std::pair <int, int>>>> // ...etc.
.
You could use a vector of some structure data type too as a substitute to tuples in the above example.
Upvotes: 0