[英]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 下面的程序是什么问题,为什么我不能使用class作为Key来初始化map
#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. 并请说明初始化地图的不同方法。
std::map
's value_type
is std::pair<const Key, T>
, means keys are saved as const
. std::map
的value_type
是std::pair<const Key, T>
,意味着密钥另存为const
。 So you can't call non-const member functions on them like std::cout<<it->first.getId()
. 因此,您不能像std::cout<<it->first.getId()
那样在它们上调用非常量成员函数。
You should change User::getId()
(and User::getUid()
) to const member functions. 您应该将User::getId()
(和User::getUid()
)更改为const成员函数。 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<
. 顺便说一句: if
条件在operator<
失败, if
您不会返回任何内容。
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;
}
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
? 您确定要将x < y
与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... 在写这个答案时,第二部分的歌谣瑶要比我快,所以看看他的答案...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.