c++ auto map iterator code example

Example 1: 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
*/

Example 2: iterar un map 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

Tags:

Java Example