std::map and operator<

If you make a map<key,value>. Is it necessary for the key datatype to have the operator< defined? Given that a std::map is sorted on keys.
If the key is not LessThanComparable (or if we want a different criterion for comparing keys), we can provide a custom BinaryPredicate which specifies how the keys are to be compared.
https://en.cppreference.com/w/cpp/named_req/Compare

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <cstring>
#include <map>

struct location
{
    const char* file_name ;
    int line_number ;
};

#define LOCATION() location{ __FILE__, __LINE__ }

struct cmp_location
{
    bool operator() ( const location& a, const location& b ) const
    {
        const auto result = std::strcmp( a.file_name, b.file_name ) ;
        if( result < 0 ) return true ;
        else if( result > 0 ) return false ;
        else return a.line_number < b.line_number ;
    }
};

int main()
{
    std::map< location, int, cmp_location > my_map ;

    my_map[ LOCATION() ] = 128 ;
    my_map[ LOCATION() ] = 229 ;
    my_map[ LOCATION() ] = 330 ;

    my_map[ LOCATION() ] = 532 ;

    for( const auto& [key,data] : my_map )
    {
        std::cout << "key: { file:" << key.file_name << ", line:" << key.line_number
                  << " }  data: " << data << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/330a0e4fe871f4db
Topic archived. No new replies allowed.