A contradiction in the C ++ standard?

A std::map must satisfy the requirements of the associative container specified in clause 23.1.2 / 2:

Each associative container is parameterized by key and ordering. A relation that causes strict weak ordering (25.3) on the Key elements. In addition, the map and multimap map an arbitrary type T with a key. An object of type Compare is called a container comparison object. This comparison object may be a pointer to a function or object of a type with the corresponding function call operator.

But then in paragraph 23.3.1 / 2, the std::map template is specified as:

 template <class Key, class T, class Compare = less<Key>, class Allocator = allocator<pair<const Key, T> > > class map; 

which explicitly prohibits the use of the function pointer like Compare . Is this a contradiction or am I misunderstanding the standard?

EDIT: Yes, the problem I really ran into is why the code, for example, GMan:

 struct foo { int x; }; bool compare_foo(const foo& x, const foo& y) { return xx < yx; } std::map<foo, bool, compare_foo> fooMap; 

will not compile (yes, I stupidly mixed the type and value of the Compare parameter).

+2
source share
4 answers

Compare the type of comparator. The fact that it is declared using class instead of typename does not matter, you can have a pointer to a type function and provide your function in the map constructor.

 #include <map> bool myCmp(int a, int b) { return a < b; } void foo() { std::map<int, char*, bool (*)(int, int)> m(myCmp); } 
+7
source

It:

 class Compare 

does not mean Compare should be a class. Maybe it would be clearer if he said:

 typename Compare 

You can use any type that provides comparable semantics for function calls, such as a function pointer.

+5
source

Indicate it as follows:

 struct foo { int x; }; bool compare_foo(foo x, foo y) { return xx < yx; } // vvvvvvvvvvvvvvvvv function pointer type std::map<foo, bool, bool(*)(foo, foo)> fooMap(compare_foo); // function pointer value ^^^^^^^^^^^ 
+3
source

You confuse the type and value of the comparator; use this for example:

 int main() { std::map<foo, bool, bool(*)(const foo&, const foo&)> fooMap(compare_foo); } 
+2
source

All Articles