使用比较运算符将 std::string 作为 std::map 中的键

Chr*_*mex 5 c++ key stdmap std stdstring

我正在尝试使用 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");
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ker 5

删除你的comparer,它会工作得很好。问题是,你没有正确实施它。true如果x要放在之前, 它应该返回y。或更改==0<0>0(这并不重要)。

  • 不客气,但您肯定对删除有误。如果将所有出现的 `std::map&lt;std::string, int, comparr&gt;` 替换为 `std::map&lt;std::string, int&gt;` ,它肯定会起作用。 (2认同)