【问题标题】:std::map with a custom class as a key returns size of 1 always以自定义类为键的 std::map 始终返回大小为 1
【发布时间】:2014-11-22 10:06:54
【问题描述】:

我正在设计一个自定义的 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;
}

虽然我在主函数中插入了两个不同的键,但映射的大小始终为 1。除了重载

【问题讨论】:

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


    【解决方案1】:
       bool size()
       {
           return errorMap.size();
       }
    

    如果你想获得不应该使用 bool 的大小。

    【讨论】:

      【解决方案2】:

      您将成员函数 size 定义为具有返回类型 bool

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

      所以返回值可以转换为整数值0或1。

      定义函数例如like

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

      【讨论】:

      • 谢谢。从我这边看,这是一个愚蠢的错误。尺寸部分现在工作正常。我也更新了插入代码。
      • @Pradeep Nayak 还要考虑到成员函数 insert 也应该返回一个值或者应该定义为返回类型为 void。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多