Iterate through unordered map C++

Yoda picture Yoda · Apr 5, 2014 · Viewed 55.8k times · Source

I have wrote program which reads input until you hit ',' - COMA at the input. Then it counts the number of letters you put in,

I want to iterate through this map but it says that it cannot be defined wih no type:

#include <iostream>
#include <conio.h>
#include <ctype.h>

#include <iostream>
#include <string>
#include <tr1/unordered_map>
using namespace std;

int main(){
    cout<<"Type '.' when finished typing keys: "<<endl;
    char ch;
    int n = 128;
    std::tr1::unordered_map <char, int> map;


    do{
      ch = _getch();
    cout<<ch;
      if(ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z'){
            map[ch] = map[ch] + 1;
      }
    } while( ch != '.' );

    cout<<endl;

    for ( auto it = map.begin(); it != map.end(); ++it ) //ERROR HERE
        std::cout << " " << it->first << ":" << it->second;


    return 0;
}

Answer

Dorin Lazăr picture Dorin Lazăr · Aug 12, 2017

With C++17 you can use a shorter, smarter version, like in the code below:

unordered_map<string, string> map;
map["hello"] = "world";
map["black"] = "mesa";
map["umbrella"] = "corporation";
for (const auto & [ key, value ] : map) {
    cout << key << ": " << value << endl;
}