2012-05-28 17 views
1

Possible Duplicate:
Why isn't the [] operator const for STL maps?真的想與地圖

我煮下來到(我認爲是)最簡單的形式,以環繞一個「常量」的問題我的頭:

#include <iostream> 
#include <map> 
#include <vector> 

class NumberHolder 
{ 
public: 
    NumberHolder(const std::string aKey, const double aNumber); 
    void printSmallestMappedNumber(const unsigned int theIndex) const; 
private: 
    std::vector< std::map< std::string, double> > theNamedNumberMapVector; 
}; 

NumberHolder::NumberHolder(const std::string key, const double aNumber) 
{ 
    std::map<std::string, double> aTempMap; 
    aTempMap[key] = aNumber; 
    theNamedNumberMapVector.push_back(aTempMap); 
} 

void NumberHolder::printSmallestMappedNumber(const unsigned int theIndex) const 
{ 
    std::map<std::string, double>& aSpecificMap = theNamedNumberMapVector[theIndex]; 
    std::cout << aSpecificMap["min"] << std::endl; 
} 

int main(int argc, char* argv[]) 
{ 
    NumberHolder aTaggedNumberHolder("min", 13); 
    aTaggedNumberHolder.printSmallestMappedNumber(0); 
    return 0; 
} 

我有一個矢量完整的地圖,並且每個地圖都充滿(字符串)「標記」數字。我試圖控制訪問所涉及變量的可見性/可變性。

總之,編譯器失敗,此錯誤

Binding of reference to type 'std::map' to a value of type 'const std::map, double, std::less >, std::allocator, double> > >' drops qualifiers

我的第一個(underbaked)試圖使地圖常量......,因爲我不會修改地圖,只是從中獲取的值:

const std::map<std::string, double>& aSpecificMap = theNamedNumberMapVector[theIndex]; 

,然後給我看,這個無可非議短,但實際上更多的confusering錯誤:

No viable overloaded operator[] for type 'const std::map<std::string, double>' 

在以下行:

std::cout << aSpecificMap["min"] << std::endl; 

然而,也許是因爲我一直在試圖解開這個了一下,我的解決方案似乎是非常,非常這些混沌:

std::map<std::string, double>& aSpecificMap = const_cast<std::map<std::string, double>&>(theNamedNumberMapVector[theIndex]); 

const_casting走[const derp]限定符適用於我的問題,但我真的很想清楚地瞭解到底發生了什麼。我猜測編譯器對我對地圖的訪問感到不滿(在我的第二次嘗試中),並認爲我會使用&濫用我對地圖內容的訪問。我真的很喜歡/需要能夠向其他人解釋這樣的內容,並且儘量不要濫用語言,最終最終落在The Daily WTF上,因爲,你知道,羞恥和內容。

+5

坦率地說,問題中存在太多無關的廢話。人們不想浪費時間閱讀所有這些;他們只是想要問題。 – chris

+0

很抱歉,克里斯..這個話題真的很乾燥,我試圖在這個週末晚上(PST)上稍微減輕一點。我嘗試了一些TL; DR(甚至是大寫!)顯然也失敗了 - 道歉。 – hEADcRASH

+1

@ hEADcRASH,我們仍然重視幽默,但是當它真的會減損真正的問題時,我們仍然不會。也許最值得注意的例外是評分最高的C++問題,http://stackoverflow.com/questions/1642028/what-is-the-name-of-this-operator。如果你環顧四周,你會看到評論評級很高,因爲它們很有趣,並不是因爲它們有幫助。這完全是在適度使用它。 – chris

回答

5

,你會看到,它不是const合格的,這就是爲什麼它不能在const std::map<std::string, double>上被調用。它不是const的原因是因爲如果密鑰不存在於地圖中,它會創建它。您應該改用findat來獲取元素。

+0

完美,謝謝 - 完全忘記了可以創建密鑰(如果它不存在)。再次感謝。 – hEADcRASH

0

map<>::operator[]在地圖中創建元素(如果它們尚不存在),這就是爲什麼在const對象上不允許它的原因。您應該使用find()

(有些鏈接的,正確的問題已經回答這個問題:例如:Why isn't the [] operator const for STL maps? - 我會投票關閉此爲重複的)。如果你看一下聲明地圖的operator[]

+0

是的,當然,託尼..我做了一個搜索(誠實的引擎!),沒有看到..或錯過它 - 我一直在盯着程序員字體遠今天太長了。 – hEADcRASH