2

I have a basic enum declaration:

enum Title {Prof, Dr, Mr, Mdm, Mrs, Miss, NA};

I've managed to map the user input from 0 to 5 with value from enum list respectively:

std::map<std::string,Title> m;
m["0"] = Prof;
m["1"] = Dr;
m["2"] = Mr;
m["3"] = Mdm;
m["4"] = Mrs;
m["5"] = Miss;
m[???] = NA; // What should I do here    

std::string stitle;

cout << "\n" << "Title (0:Prof 1:Dr 2:Mr 3:Mdm 4:Mrs 5:Miss Any:NA): ";
cin >> stitle;
Title title = m[stitle];

How can I map the user input such as 6, 7 or any input beside 0 to 5 with NA value from the enum list?

Pewds
  • 65
  • 1
  • 5

3 Answers3

3

You cannot. You can just use find, instead of operator [].

std::map<std::string, Title>::iterator pos = m.find(stitle);
Title title = pos == m.end() ? NA : pos->second;
ForEveR
  • 55,233
  • 2
  • 119
  • 133
  • Thank you for your answer. May I ask what's the meaning of `pos->second` here? – Pewds Jul 16 '15 at 12:08
  • @Pewds std::map stores pairs, so, pos->second actually means (*pos).second, that means dereference iterator, get pair and get second element from pair. – ForEveR Jul 16 '15 at 12:10
  • Thank you for your explanation, great answer :D – Pewds Jul 16 '15 at 12:21
1

Instead of using operator[], which will implicitly add an entry for a key if it does not exist, I would use at, which throws an exception instead:

Title title;
try {
    title = m.at(stitle);
}
catch (const std::out_of_range& oor) {
    title = NA;
}
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
0

I think you're looking for something like

if(m.find(stitle) == m.end()) { cout << "Invalid input" << endl; //Exit here or loop again? }
else
  Title title = m[stitle];
Salgar
  • 7,687
  • 1
  • 25
  • 39