2021-03-06 字符串std::string当做映射map的键问题

问题出现场景: 定义std::map < std::string,HANDLE > mapHandles;使用mapHandle[“test”] = NULL;
报错error C2784:二进制"<":“const std::string"不定义该运算符或到预订义运算符可接收的类型的转换
error C2784:“bool std::operator<(const std::_Tree<_Traits>&const std::_Tree<_Traits>&>)”:无法从"const std::string” 为 “const std::_Tree<_Traits>&” 推导 模板 参数
问题出现原因: 若作为映射的键值,则该键类型需要有比较功能,用于映射排序,str::string在vs2005中无比较功能,所以报错。
问题解决措施: 添加比较函数,若键值是自定义类型,则需要加入比较<运算符函数,使用char*、const char作为键值比较的是指针的值,不是指针的内容即字符串,所以不能用char const char*
措施: 添加比较结构体struct StringCompareForMap{
//定义操作符函数
public:
bool operator()(const std::string x, const std::string y)
{
// Add compare logic here

}
public:
bool operator<(const std::string x, const std::string y)
{
// Add compare logic here

}
};
这样定义:std::map< std::string,HANDLE,StringCompareForMap> mapHandles;

另一种解决方法:
反正是乱七八糟的错误,原因很简单,少了 #include
(注意,不是string.h,如果包含了string.h,请改为string)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值