ssg
ssg

Reputation: 347

How can I insert key as a class in map STL in C++

What is the problem in below program, why i am not able to initialize map with class as a Key

#include <iostream>
#include <map>

#include <utility>

using namespace std;

class User
{
    int value_1;
    int value_2;
public:
    User( int num_1, int num_2)
    {
        value_1 = num_1;
        value_2 = num_2;
    }
    int getId(){
        return value_1;
    }
    int getUid(){
        return value_2;
    }
    bool operator< (const User& userObj) const
    {
        if(userObj.value_1 < this->value_1)
            return true;
    }
};

int main()
{
    std::map<User, int> m_UserInfoMap;

    m_UserInfoMap.insert(std::make_pair<User, int>(User(1,2), 100) );
    m_UserInfoMap.insert(std::make_pair<User, int>(User(3,4), 120) );
    m_UserInfoMap.insert(std::make_pair<User, int>(User(5,6), 300) );
    std::map<User, int>::iterator it = m_UserInfoMap.begin();
    for(; it != m_UserInfoMap.end(); it++)
    {
        std::cout<<it->first.getId()<<" :: "<<it->second<<std::endl;
    }
    return 0;
}

In above program if I try to add key as a class it is giving error. And please tell different ways to initialize map.

Upvotes: 0

Views: 67

Answers (2)

Aconcagua
Aconcagua

Reputation: 25516

First, you should make your operator always return a value:

bool operator< (const User& userObj) const
{
    return userObj.value_1 < this->value_1;
}

Are you sure you really want to compare x < y as y.value < x.value? Otherwise, you need to change the comparison inside:

bool operator< (const User& userObj) const
{
    return this->value_1 < userObj.value_1;
}

And while writing this answer, songyuanyao has been faster than me for the second part, so have a look at his answer...

Upvotes: 1

songyuanyao
songyuanyao

Reputation: 172894

std::map's value_type is std::pair<const Key, T>, means keys are saved as const. So you can't call non-const member functions on them like std::cout<<it->first.getId().

You should change User::getId() (and User::getUid()) to const member functions. Such as:

int getId() const {
//          ~~~~~
    return value_1;
}
int getUid() const {
//           ~~~~~
    return value_2;
}

BTW: You didn't return anything when if condition fails in operator<.

bool operator< (const User& userObj) const
{
    if(userObj.value_1 < this->value_1)
        return true;
    else
        return false;  // return for else case
}

or just

bool operator< (const User& userObj) const
{
    return userObj.value_1 < this->value_1;
}

Upvotes: 5

Related Questions