0

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 > >')

1
  • 3
    Do not tell anybody what error you are getting, that would be more interesting Commented Jun 19, 2017 at 3:36

1 Answer 1

1

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])] << " ";
Sign up to request clarification or add additional context in comments.

1 Comment

Somebody need to make a VS plugin that would redirect compiler error directly to SO, these people do not bother to read and comprehend them anyway. They do not even bother to paste error messages to their questions. Why bother, if somebody like @songyuanyao whould answer anyway?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.