2013-10-16 32 views
2

考慮下面的C++代碼:從STD檢索項::地圖在功能上打上const的

// 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]; 
} 

我怎樣才能抓住從m,使得它在一個const功能的情況下的價值?

+1

需要注意的是'運營商[]'不'const',因爲如果該鍵不存在,它被添加到具有默認值的地圖。 'operator []'不能是'const',因爲它可以改變'map'。 –

回答

7

您最好的選擇是使用at()方法,該方法是const,如果找不到密鑰,將會拋出異常。

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

否則,你將不得不決定在沒有找到密鑰的情況下返回什麼。如果你能在這些情況下返回一個值,那麼你可以使用std::map::find

int A::getValue(int key) const 
{ 
    auto it = m.find(key); 
    return (it != m.end()) ? it->second : TheNotFoundValue; 
} 
+0

另外,如果您希望在未找到密鑰時允許插入默認對象,請考慮將變量定義爲可變。 – MikeGM