user13205785
user13205785

Reputation: 89

How to iterate over an unordered map's specific key's values?

I have an unordered map with a string and a vector of strings. I want to go to a specific key and iterate over all it's values.

Ex. Go to key 400 and iterate over 1, 2, and 3.

{
    400 -> [1,2,3],
    200 -> [],
    13 -> [10,30]
}
std::unordered_map<std::string, std::vector<std::string>> mymap;
myKey = 400; 
for(auto elem: mymap){
if(elem.first == myKey){
     for(auto elem2: elem.first.size()){
       //do stuff here
     }
   }
 }

Upvotes: 2

Views: 986

Answers (1)

cigien
cigien

Reputation: 60208

You don't need 2 loops to do this. Specifically, the outer loop that looks for the key is unnecessary. If you know that the key exists, you could simply do:

for (auto const & item : mymap["400"])
  // ...

If you're not sure whether the key exists, you can write:

if (auto it = mymap.find("400");
    it != mymap.end())
  for (auto const & item : it->second)
    // ...

Or from C++20, just:

if (mymap.contains("400"))
  for (auto const & item : mymap["400"])
    // ...

Upvotes: 3

Related Questions