Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string as a key in std::map using a compare operator

I'm trying to use a std::string as a key in a std::map however, i'm unable to find() correctly. My code is somewhat complicated and large so this is a small program that demonstrates the problem I'm having. If someone could tell me why this doesn't work, i'd be very grateful.

Thanks.

#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");
}
like image 214
Chromex Avatar asked Dec 04 '11 10:12

Chromex


People also ask

Can we use string as key in map C++?

Either use std::string as the key or declare a custom string comparison predicate and include that in your map template. Note that if you do the latter, you must absolutely ensure that your manage your string pointers correctly.

How do I compare STD strings?

In order to compare two strings, we can use String's strcmp() function. The strcmp() function is a C library function used to compare two strings in a lexicographical manner. The function returns 0 if both the strings are equal or the same.

What can be used as the key of map in C++?

We can use any of the data types as the data type of the key of the map. Even a user-defined data type can be used as key data type. Now, we will create a data structure that defines a new data type. And use it as a key for the map.

Can we use string in map?

Since the String class is immutable, you cannot modify the value of a String once it is created. Therefore, it is recommended to use a String variable to hold keys in hash a map.


1 Answers

Remove your comparer and it will work just fine. The thing is, you didn't implement it properly. It should return true if x is to be placed before y. Or change ==0 to <0 or >0 (it doesn't really matter).

like image 94
Michael Krelin - hacker Avatar answered Nov 14 '22 22:11

Michael Krelin - hacker