iterate over unordered_map c++ code example

Example 1: how to iterate through a map in c++

//traditional way (long)
for(map<string,int>::iterator it=m.begin(); it!=m.end(); ++it)
	if(it->second)cout<<it->first<<" ";
//easy way(short) just works with c++11 or later versions
for(auto &x:m)
	if(x.second)cout<<x.first<<" ";
//condition is just an example of use

Example 2: how to iterate over unordered_map c++

for(auto it : umap){
  cout<< it->first << " " << it->second << endl;
}

/*
umap = [
	{1 , "Hello"},
    {2 , "world"}
]
*/


/*
 Output :
 1 Hello
 2 World
*/

Tags:

Cpp Example