繁体   English   中英

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

[英]std::string as a key in std::map using a compare operator

我正在尝试使用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");
}

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

comparer::operator()应返回operator <的值,而不是operator ==的值。

std::map (和set及其multi变量)强制执行严格的弱排序

x.compare(y) == 0;

如果字符串相等,则返回true。 比较器应该返回第一个字符串是否应该在第二个字符串之前。 返回x.compare(y) < 0或者只是让你的比较函数离开。

这应该工作:

#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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM