簡體   English   中英

使用自定義類作為鍵的std :: map總是返回1的大小

[英]std::map with a custom class as a key returns size of 1 always

我正在設計一個自定義的ErrorInfo類,可以由其他模塊實現,以實現它們的特定錯誤信息類。 錯誤在自定義映射中維護,其中鍵是由實現基類的模塊定義的自定義鍵。 鍵是基類的模板參數。

這是示例基類和派生類。

#include <iostream>
#include <vector>
#include <string>
#include <map>
using namespace std;

template <class K>
class ErrorInfo {
 public:
        ErrorInfo(){};
        void setTraceAll()
        {
            _traceAll = true;
        }

        bool isSetTraceAll()
        {
            return _traceAll;
        }


       bool insert(K key, int i)
       {
            errorMap.insert(std::pair<K,int>(key,i));
       }

       bool size()
       {
           return errorMap.size();
       }

    private:
        std::map<K, int> errorMap;
        bool _traceAll;
};

class MyCustomKey
{
    private:
        int _errorCode;
    public:
        MyCustomKey(int errorCode): _errorCode(errorCode).
        {
        }

        bool operator<(const MyCustomKey &rhs) const
        {
           return _errorCode < rhs._errorCode;
        }

};

class MyCustomErrroInfo: public ErrorInfo<MyCustomKey>
{
    public:
        MyCustomErrroInfo(){};

};

int main(){
    MyCustomErrroInfo a;
    a.insert(MyCustomKey(1), 1);
    a.insert(MyCustomKey(2), 2);
    cout<<"Size: "<<a.size()<<endl;
}

雖然我在main函數中插入了兩個不同的鍵,但是地圖的大小始終是1.除了重載<operator之外我不知道我在這里缺少什么。 對我可能做錯的任何幫助都將不勝感激。

   bool size()
   {
       return errorMap.size();
   }

如果你想獲得尺寸,你不應該使用bool ..

您將成員函數size定義為具有返回類型bool

   bool size()
   {
       return errorMap.size();
   }

因此,返回值可以轉換為0或1的整數值。

定義函數例如

   size_t size()
   {
       return errorMap.size();
   }

成員函數insert也不返回任何內容

   bool insert(K key, int i)
   {
        errorMap.insert(std::pair<K,int>(key,i));
   }

應該是這樣的

   bool insert(K key, int i)
   {
        return errorMap.insert(std::pair<K,int>(key,i)).second;
   }

暫無
暫無

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

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