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

std::map<std::string
c++ map get value
initialize map c++
std::map compare
c++ map::find
c++ map check if key exists
map< char , int c
c++ map unique key

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");
}

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

Use custom objects as keys to std::map in C++, In this post, we will see how to use custom objects as keys to std::map in C++. have to tell the map how to compare the two objects using a comparison function in the third parameter of std::map template. overload < operator to use a Node object as a key in a std::map std::map<Node<std::string,std::string>, int> map =. In order to use any object as a key in std::map, we have to tell the map how to compare the two objects using a comparison function in the third parameter of std::map template. The default value of the third parameter is std::less which delegates the comparison to operator< defined for the key type of the map.

comparer::operator() should return value of operator <, not of operator ==.

3 ways to use std::pair as a key to std::map in C++, Since the operator< is already defined for pairs, we can initialize a std::map with typedef std::pair<std::string,std::string> pair; The comparison object takes two pair objects and defines the ordering of map's keys by comparing the first and  1) Copy assignment operator. Replaces the contents with a copy of the contents of other. If std:: allocator_traits < allocator_type >:: propagate_on_container_copy_assignment:: value is true, the target allocator is replaced by a copy of the source allocator.

std::map (and set and their multi variants) enforce strict weak ordering.

x.compare(y) == 0;

Will return true if the strings are equal. The comparer should return whether the first string should go before the second string. Either return x.compare(y) < 0 or just leave your comparision functor out.

map - C++ Reference, std::map. template < class Key, // map::key_type class T, // map::mapped_type class Compare = less<Key>, The mapped values in a map can be accessed directly by their corresponding key using the bracket operator ((operator[]). Maps are value_compare, Nested function class to compare elements, see value_comp. However, one implementation (libc++) is known to construct the key_type and mapped_type objects via two separate allocator construct() calls, as arguably required by the standards as published, rather than emplacing a value_type object. operator[] is non-const because it inserts the key if it

This should work:

#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");
}

map::key_comp - C++ Reference, By default, this is a less object, which returns the same as operator< . Member type key_compare is the type of the comparison object associated to the map::​key_comp #include <iostream> #include <map> int main () { std::map< char , int > key value of last element std::map< char , int >::iterator it = mymap.begin(); do  Returns a copy of the comparison object used by the container to compare keys. The comparison object of a map object is set on construction. Its type (member key_compare) is the third template parameter of the map template. By default, this is a less object, which returns the same as operator<. This object determines the order of the elements

std::map<Key,T,Compare,Allocator>::operator , std::map<Key,T,Compare,Allocator>::operator[] first call to operator[] initialized the counter with zero) std::map<std::string, size_t> word_map;  By default std::map uses “operator <” as sorting criteria for keys. For default data types like int and std::string etc, operator < is available by default but for User defined classes operator < is not available by default. Therefore, to use user defined class objects as keys in std::map we should have either,

std::map, map::operator= · map:: using map = std::map<Key, T, Compare, std::map is a sorted associative container that contains key-value pairs with  As no external sorting criteria for key(std::string) is specified in above std::map, therefore it will use default key sorting criteria i.e operator < and all elements will be arranged inside std::map in alphabetical sorted order of keys.

C++ : Map Tutorial Part 3: Using User defined class objects as keys , To use this class as key in std::map we will overload operator <. const std::​string& getName() const { Now suppose we want to change the sorting criteria of keys i.e for User objects, instead of comparing by ID we want to  This article explains how to implement a map with case-insensitive string keys. What do I mean by that? Let's look at the situation below. Imagine, I have a map storing precipitation of individual U.S. states.

Comments
  • I changed the comparer to return x.compare(y)<0; and it worked fine, thank you. Removing the comparer didn't work btw. #SOLVED.
  • You're welcome, but you're sure mistaking about the removal. If you replace all occurences of std::map<std::string, int, comparer> with std::map<std::string, int> it will sure work.
  • The problem I am having in my main application is that I have to check for duplicates in the map before adding a new pair. However, it is not detecting the duplicates properly
  • I was talking about this code, not your application, of course. As for duplicates, map isn't allowed to have any unlike multimap.
  • actually this doesn;t seem to be the case, when i add two pairs that have the same key value, iterating through the map shows 2 entries with the same key.