我正在尝试使用std :: string作为std :: map中的键,但是我无法正确找到().我的代码有点复杂和大,所以这是一个小程序,演示了我遇到的问题.如果有人能告诉我为什么这不起作用,我将非常感激.
谢谢.
#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");
}
解决方法:
删除你的比较器,它会工作得很好.问题是,你没有正确实现它.如果要将x放在y之前,它应该返回true.或者将== 0改为< 0或> 0(这并不重要).
标签:c,key,std,stdstring,stdmap 来源: https://codeday.me/bug/20190726/1540861.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。