[英]std::string as a key in std::map using a compare operator
I'm trying to use a std::string as a key in a std::map however, i'm unable to find() correctly. 我正在尝试使用std :: string作为std :: map中的键,但是我无法正确找到()。 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. 如果有人能告诉我为什么这不起作用,我将非常感激。
Thanks. 谢谢。
#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");
}
Remove your comparer
and it will work just fine. 删除你的comparer
,它会工作得很好。 The thing is, you didn't implement it properly. 问题是,你没有正确实现它。 It should return true
if x
is to be placed before y
. 如果要将x
放在y
之前,它应该返回true
。 Or change ==0
to <0
or >0
(it doesn't really matter). 或者将==0
更改为<0
或>0
(这并不重要)。
comparer::operator()
应返回operator <的值,而不是operator ==的值。
std::map
(and set
and their multi
variants) enforce strict weak ordering . std::map
(和set
及其multi
变量)强制执行严格的弱排序 。
x.compare(y) == 0;
Will return true if the strings are equal . 如果字符串相等,则返回true。 The comparer should return whether the first string should go before the second string. 比较器应该返回第一个字符串是否应该在第二个字符串之前。 Either return x.compare(y) < 0
or just leave your comparision functor out. 返回x.compare(y) < 0
或者只是让你的比较函数离开。
This should work: 这应该工作:
#include <stdio.h>
#include <string>
#include <map>
struct comparer
{
public:
bool operator()(const std::string x, const std::string y) const
{
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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.