Reputation: 18068
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 with 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
cout << " " << it->first << ":" << it->second;
return 0;
}
Upvotes: 15
Views: 98724
Reputation: 917
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;
}
Upvotes: 3
Reputation: 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. mymap
So 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;
Upvotes: 28
Reputation: 824
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;
}
Upvotes: 40
Reputation: 45414
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
...
Upvotes: 4