Iterate through unordered map C++

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;
}
2

4 Answers

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;
}
1

You are using auto so you have C++11 code. You need a C++11 compliant compiler (e.g. GCC 4.8.2 or newer). As Peter G. commented, don't name your variable map (which is std::map) but e.g. mymapSo please

#include <unordered_map>

(no need for tr1!)

Then compile with g++ -std=c++11 -Wall -g yoursource.cc -o yourprog and code a range based for loop

for (auto it : mymap) std::cout << " " << it.first << ":" << it.second << std::endl;
3

Add -std=c++11 to your compiler flags (with gcc/icc/clang) if you want to use auto (and other C++11 features). Btw, unordered_map is in std in C++11 ... Also there is std::isalpha ...

Based on Dorin Lazăr answer, another possible solution is:

unordered_map<string, string> my_map;
my_map["asd"] = "123";
my_map["asdasd"] = "123123";
my_map["aaa"] = "bbb";
for (const auto &element : my_map) { cout << element.first << ": " << element.second << endl;
}
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like