Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I fix this error message error: no match for ‘operator[]’

I am implementing a class that involves unordered_sets, and unordered_maps. When I go to run the program it gives me the following error

error: no match for ‘operator[]’ (operand types are ‘std::unordered_set<std::__cxx11::basic_string<char> >’ and ‘const string’ {aka ‘const std::__cxx11::basic_string<char>’})
     int points = Prizes[Codes[code]]->points;

I am unsure of how to fix this, please help.

I have pasted my function (sightly condensed) below.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int Code_Processor::Enter_Code(const string &username, const string &code) {
    User *user = user_iter->second;
    int points = Prizes[Codes[code]]->points;
    user->points += points;
    Codes.erase(code);
    return points;
}

I have also included part of the header file below.

class User {
  public:
     std::string username;
     std::string realname;
     int points;
     std::set <std::string> phone_numbers;
};

class Prize {
  public:
     std::string id;
     std::string description;
     int points;
     int quantity;
};

class Code_Processor {
  public:
    int Enter_Code(const std::string &username, const std::string &code);

  protected:
    std::unordered_map <std::string, User *> Names;
    std::unordered_map <std::string, User *> Phones;
    std::unordered_set <std::string> Codes;
    std::unordered_map <std::string, Prize *> Prizes;
};

>Solution :

The class template std::unordered_set does not have the subscript operator.

You could write for example

if ( Codes.find( code ) != Codes.end() )
{
    int points = Prizes[code]->points;
    user->points += points;
    Codes.erase(code);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading