Re: Inserting objects into a std::map?
On Mar 27, 10:04 pm, Paul Brettschneider
I am reading section 23 in the C++ standard and cannot seem
to find where it says that the key_type must be defined for
'<' when inserting into std::map.
It is described in The C++ Programming Language 3th ed so I assume I
just can't find it.
It's very indirect. The requirements for an associative
container specify the requirements of a Compare type, which
defines the ordering, and the requirements are that it can be
called with two key_type, will return a bool, and that if that
bool is interpreted as meaning that the first object is strictly
ordered before the second, then the type establishes the
necessary ordering relationship. There is no requirement for
the < operator (and many of my keys for sets don't support it).
In the specifications for std::map, the Compare type is the
third template parameter, and defaults to std::less<key_type>.
And std::less requires a < operator, unless explicitly
The only time you need a < operator is thus if you use the
default third parameter and haven't explicitly specialized
std::less for the type.
Another thing. When I make:
std::map<Bob, int> m;
And my Bob class does not define '<' operator why does the
compiler not complain in the above declaration of 'm'?
Its first when I insert that the compiler complains about
the missing operator in Bob:
It's the way templates work: functions/methods are only
instantiated when you use them. Since Key::operator<() is not
needed for constructing an empty map, the compiler doesn't
Or it does (g++, for example). The current standard says it's
undefined behavior, so anything the implementation does is
This will probably change with the C++0x contracts-feature.
I think the word you're looking for is concepts. And yes, the
goal is to require errors in cases which are now undefined
James Kanze (GABI Software) email:email@example.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34