Manjunath
Manjunath

Reputation: 541

unordered_map is unable to retrieve value for a key specified as a variable in argument

I need to extract specific values from the unordered_map. However, unordered_map is unable to lookup with a variable inside its box brackets.

In the below code cout << m[code[i]] << " "; is throwing an error.

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main()
{
    string code;
    cout << "Enter code: ";
    getline(cin, code);

    unordered_map<string, string> m = {
        {"A","Jan"},{"B","Feb"},{"C","Mar"},{"D","Apr"},
        {"E","May"},{"F","Jun"},{"G","Jul"},{"H","Aug"},
        {"I","Sep"},{"J","Oct"},{"K","Nov"},{"L","Dec"}
    };

    for(int i=0 ; i<code.length() ; i++) {
        cout << m[code[i]] << " ";
    }

    return 0;
}

Error msg:

main.cpp:18:18: No viable overloaded operator[] for type 'unordered_map' (aka 'unordered_map, allocator >, basic_string, allocator > >')

Upvotes: 0

Views: 381

Answers (1)

songyuanyao
songyuanyao

Reputation: 172894

Given code with type string, code[i] returns a char (but not a string); which doesn't match the key type of the map.

You can change the type of map to unordered_map<char, string>, e.g.

unordered_map<string, string> m = {
    {'A',"Jan"},{'B',"Feb"},{'C',"Mar"},{'D',"Apr"},
    {'E',"May"},{'F',"Jun"},{'G',"Jul"},{'H',"Aug"},
    {'I',"Sep"},{'J',"Oct"},{'K',"Nov"},{'L',"Dec"}
};

If you want to work with unordered_map<string, string>, you have to pass a string to unordered_map::operator[]. e.g.

cout << m[string(1, code[i])] << " ";

Upvotes: 1

Related Questions