使用比较运算符将std :: string作为std :: map中的键 [英] std::string as a key in std::map using a compare operator
本文介绍了使用比较运算符将std :: string作为std :: map中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用std :: string作为std :: map中的键,但是,我无法正确找到().我的代码有些复杂而且很大,所以这是一个小程序,演示了我遇到的问题.如果有人能告诉我为什么这行不通,我将非常感激.
I'm trying to use a std::string as a key in a std::map however, i'm unable to find() correctly. My code is somewhat complicated and large so this is a small program that demonstrates the problem I'm having. If someone could tell me why this doesn't work, i'd be very grateful.
谢谢.
#include <stdio.h>
#include <string>
#include <map>
struct comparer
{
public:
bool operator()(const std::string x, const std::string y)
{
return x.compare(y)==0;
}
};
int main(int argc, char *argv[])
{
std::map<std::string, int, comparer> numbers;
numbers.insert(std::pair<std::string,int>("One",1));
numbers.insert(std::pair<std::string,int>("Two",2));
numbers.insert(std::pair<std::string,int>("Three",3));
numbers.insert(std::pair<std::string,int>("Four",4));
numbers.insert(std::pair<std::string,int>("Five",5));
std::map<std::string, int, comparer>::iterator it=numbers.find("Three");
if(it!=numbers.end())
printf("The number is %d\n",(*it).second);
else
printf("Error, the number is not found\n");
}
推荐答案
删除您的comparer
,它将正常工作.问题是,您没有正确实现它.如果将x
放置在之前 y
,则应返回true
.或将==0
更改为<0
或>0
(这并不重要).
Remove your comparer
and it will work just fine. The thing is, you didn't implement it properly. It should return true
if x
is to be placed before y
. Or change ==0
to <0
or >0
(it doesn't really matter).
这篇关于使用比较运算符将std :: string作为std :: map中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文