johnbakers
johnbakers

Reputation: 24750

How to create const member function that accesses std::map item

I am trying to merely return, not alter, the value in a std::map. It works, but if I put const on the function, as it should be, I get the error No viable overloaded operator[] for type 'const std::map. My code is as follows:

GLuint getCurrentColorAttribute() const {
    return m_programs[m_currentActiveProgram].attributes["SourceColor"];
}

Here is an image of the error in my IDE: enter image description here

Upvotes: 3

Views: 419

Answers (1)

Tushar
Tushar

Reputation: 8049

The [] operator of std::map isn't const (because it can create a new entry in the map if one doesn't exist), and thus you can't call it from a const function.

You can use at instead in C++11:

return m_programs.at(m_currentActiveProgram).attribute["SourceColor"];

Upvotes: 5

Related Questions