how can i get keys for such a map map<string,vector<string>>mymap assuming that mymap["index"]={"val1","val2"}? I have found the solution here for a normal map like map<string,string> but for this i don't know how to do it.
- 2What do you mean by "get keys"? And how is this different from a "normal map"?Andy Prowl– Andy Prowl2013-03-10 11:06:37 +00:00Commented Mar 10, 2013 at 11:06
- map["index"].vector_method ....? aka map["index"].at(0) will access the first string? / map["index"].push_back("hello");user1182183– user11821832013-03-10 11:07:41 +00:00Commented Mar 10, 2013 at 11:07
- Yes, and i want to get the 'index'.siloan– siloan2013-03-10 11:18:38 +00:00Commented Mar 10, 2013 at 11:18
2 Answers
You can iterate through all the values in the map (which are pairs) and refer their first and second element to obtain, respectively, the key and the mapped value:
#include <map> #include <vector> #include <string> int main() { std::map<std::string, std::vector<std::string>> m; // ... for (auto& p : m) { std::string const& key = p.first; // ... std::vector<std::string>& value = p.second; // ... } } Of course, you could achieve the same using std::for_each instead:
#include <map> #include <vector> #include <string> #include <algorithm> int main() { std::map<std::string, std::vector<std::string>> m; // ... std::for_each(begin(m), end(m), [] ( std::pair<std::string const, std::vector<std::string>>& p // ^^^^^ // Mind this: the key is constant. Omitting this would // cause the creation of a temporary for each pair ) { std::string const& key = p.first; // ... std::vector<std::string>& value = p.second; // ... }); } Finally, you may also roll your own manual for loop, although I personally consider this less idiomatic:
#include <map> #include <vector> #include <string> int main() { std::map<std::string, std::vector<std::string>> m; // ... for (auto i = begin(m); i != end(m); ++i) { std::string const& key = i->first; // ... std::vector<std::string>& value = i->second; // ... } } This is how the last example above would look like in C++03, where type deduction through auto is not supported:
#include <map> #include <vector> #include <string> int main() { typedef std::map<std::string, std::vector<std::string>> my_map; my_map m; // ... for (my_map::iterator i = m.begin(); i != m.end(); ++i) { std::string const& key = i->first; // ... std::vector<std::string>& value = i->second; // ... } } 7 Comments
The map holds std::pair<key_type, mapped_type> internally, so iterating over the map gives you access to the keys via it->first, where it is the iterator.
std::map<std::string, std::vector<string>> m; for (auto it = m.cbegin(), it != m.cend(); ++it) std::cout << "key " << it->first << std::endl; The range based loop version is
for (const auto& stuff : m) std::cout << "key " << stuff.first << std::endl;