簡體   English   中英

C ++ unordered_map導致編譯時錯誤

[英]C++ unordered_map causing compile-time error

我有以下內容:

#include<iostream>
#include<unordered_map>
#include<tuple>

using namespace std;

class CTest {
    // Properties
    public:
        unordered_map<const string, tuple<int, int> > Layout;
    // Methods
    public:
        CTest ();
        ~CTest ();
};

CTest::CTest () {
    Layout["XYZ"] = make_tuple (0, 1);
}

CTest::~CTest () {
  // Do nothing
}

int main (int argc, char *argv[]) {
    CTest Test;
    return 0;
}

編譯這個簡單的程序會出現以下錯誤:

錯誤C2678:二進制'==':找不到哪個運算符帶有'const std :: string'類型的左操作數(或者沒有可接受的轉換)

我在Windows 7中使用Visual Studio 2010 Professional。

除了將Layout更改為:

unordered_map<string, tuple<int, int> > Layout;

如Johan和Benjamin所述,你還需要#include <string>

注意,我不明白為什么需要更改Layout ,即使const是多余的。

您需要刪除鍵上的const限定符。

unordered_map<const string, tuple<int, int> > Layout;

unordered_map<string, tuple<int, int> > Layout;

這是因為根據這個答案,鍵總是const:

對unordered_map使用const鍵

我認為潛在的原因與C中允許的重復const限定符有關, 但在C ++中卻沒有?

此外,正如其他帖子所指出的那樣你可能需要包含字符串(盡管gcc似乎帶有iostream)

正如所指出的,您的初始錯誤的原因是您需要包含<string> 但是,您可能還有另一個問題:

unordered_map<const string, tuple<int, int> > Layout;

您(可能)需要從該字符串中刪除const:

unordered_map<string, tuple<int, int> > Layout;

這可能不是您的編譯器所必需的,但它在我的編譯器上。 首先,const是多余的,map / unordered_map鍵無論如何都是const,但這不是問題。 問題與散列函數模板有關,不適用於const類型。

以下簡單程序為我隔離了問題:

#include <functional>
int main (int argc, char *argv[])
{
    std::hash<const int> h;
    h(10);
}

http://ideone.com/k2vSy

undefined reference to `std::hash<int const>::operator()(int) const'

我現在不能解釋這個。

只要#include <string> ,Visual Studio 2010就會按原樣編譯源代碼,以便它可以對string進行比較測試。

正如其他海報所提到的那樣,你也應該使你的密鑰成為常規string而不是const string ,因為這符合STL標准,但這並不是使VS 2010編譯上述源代碼所必需的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM