我想在std::map中使用std::string作为键,但是我无法正确地使用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");
}
std::map<std::string, int, comparer>
的出现替换为std::map<std::string, int>
,那么它一定会起作用。 - Michael Krelin - hackermap
不允许有任何重复项,而multimap
则可以。 - Michael Krelin - hacker