【发布时间】:2012-01-12 13:45:18
【问题描述】:
我正在尝试使用 std::string 作为 std::map 中的键,但是,我无法正确地 find()。我的代码有点复杂而且很大,所以这是一个演示我遇到的问题的小程序。如果有人能告诉我为什么这不起作用,我将非常感激。
谢谢。
#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");
}
【问题讨论】:
标签: c++ key std stdstring stdmap