Question

Consider the following C++ code:

// A.h
class A {
private:
    std::map<int, int> m;
    int getValue(int key) const;
};

// A.cpp
int A::getValue(int key) const {
    // build error: 
    // No viable overloaded operator[] for type 'const std::map<int, int>'
    return m[key];
}

How can I grab the value from m such that it works in the context of a const function?

Was it helpful?

Solution

Your best option is to use the at() method, which is const and will throw an exception if the key is not found.

int A::getValue(int key) const 
{
  return m.at(key);
}

Otherwise, you would have to decide what to return in the case where the key is not found. If there is a value you can return in these cases, then you can use std::map::find:

int A::getValue(int key) const 
{
  auto it = m.find(key);
  return (it != m.end()) ? it->second : TheNotFoundValue;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top