Pradeep Nayak
Pradeep Nayak

Reputation: 675

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

I am designing a custom ErrorInfo class which can be implemented by other modules to implement their specific error info class. The errors are maintained in a custom map where the key is a custom key defined by the module which is implementing the base class. The key is a template argument to the base class.

Here is the sample base class and a derived class.

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

Although I am inserting two different keys in the main function, the size of the map is always 1. Other than overloading the < operator I am not sure what I am missing here. Any help on what I might be doing wrong would be appreciated.

Upvotes: 1

Views: 197

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

You defined member function size as having return type bool

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

So the return value can be converted to an integral value either 0 or 1.

Define the function for example like

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

Also member function insert returns nothing

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

It should look like

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

Upvotes: 1

CodingMadeEasy
CodingMadeEasy

Reputation: 2337

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

If you want to get the size you shouldn't be using bool..

Upvotes: 2

Related Questions