Using user defined type as key in std::map
-
Hi All,
When we use user defined type as key in std::map, we are forced to overload < operator, which I could understand the reason for it.
But I could not understand the reason why the < operator overloading should be const function.Can some one please help me understand the reason why std::map is expecting the const function for < overloading ?
Regards!
-
@Vinoth-Rajendran4
Then surely you just need to Googlestd::map
?The first hit takes you to cppreference.com, which is thorough. On https://en.cppreference.com/w/cpp/container/map
template< class Key, class T, class Compare = std::less<Key>, class Allocator = std::allocator<std::pair<const Key, T> > > class map;
So click on
std::less
. https://en.cppreference.com/w/cpp/utility/functional/lessbool operator()( const T& lhs, const T& rhs ) const; (until C++14) constexpr bool operator()( const T& lhs, const T& rhs ) const; (since C++14)
So now you know it's
const
. -
because the boolean return value of the operator overload is expected to be const by the std::map template. C++ went bat-crap crazy with const a few years back, as if making EVERYTHING const somehow creates superior code. It's part of a larger problem, the belief among the younger crowd that the more code it takes to express an idea, the "better" it is. kind of like the mistaken assumption that 32-64 character identifiers are better. than single character loop control vars like (X,Y,Z,I,C)...
-
Thanks @Kent-Dorfman for the reply,
because the boolean return value of the operator overload is expected to be const by the std::map template.
Like to know, if there is any document where I could refer, on the return value expected to be constant ?
-
@Vinoth-Rajendran4 said in Using user defined type as key in std::map:
But I could not understand the reason why the < operator overloading should be const function
Why should it not?
The comparision operator should not change the objects it compares (it would else introduce side effects which are hard to discover), so it is declared const.
Also, const can help compiler to optimise code. -
@Vinoth-Rajendran4
Then surely you just need to Googlestd::map
?The first hit takes you to cppreference.com, which is thorough. On https://en.cppreference.com/w/cpp/container/map
template< class Key, class T, class Compare = std::less<Key>, class Allocator = std::allocator<std::pair<const Key, T> > > class map;
So click on
std::less
. https://en.cppreference.com/w/cpp/utility/functional/lessbool operator()( const T& lhs, const T& rhs ) const; (until C++14) constexpr bool operator()( const T& lhs, const T& rhs ) const; (since C++14)
So now you know it's
const
.