簡體   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