使用自定义类作为键的std :: map总是返回1的大小

时间:2014-11-22 10:06:55

标签: c++ templates c++11 operator-overloading stdmap

我正在设计一个自定义的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函数中插入了两个不同的键,但是map的大小始终是1.除了重载&lt;运营商我不确定我在这里缺少什么。对我可能做错的任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:2)

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

如果你想获得大小,你不应该使用bool ..

答案 1 :(得分:1)

您将成员函数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;
   }