why this program can get compiled using g++ without any complain?

Y

yuyang08

Hi,

I wrote a simple program to learn the usage of STL template
map and set. Although I did not give out any Compare function
with respect to struct A, the program got compiled without
any complain using g++. Could you explain why?

Many thanks!

#include <iostream>
#include <map>
#include <set>
using namespace std;

struct A{
int x, y;
};

int main()
{
A a1, a2;
a1.x = 5; a1.y = 6;
a2.x = 7; a2.y = 8;
map< pair<A*, A*> , int> test;
set< pair<A*, A*> > haha;
test.insert( make_pair( make_pair(&a1, &a2), 6) );
haha.insert( make_pair(&a1, &a2) );
return 0;
}
 
P

Phlip

yuyang08 said:
map< pair<A*, A*> , int> test;

(Tip: always use a typedef for non-trivial templated types.)

That map contains pointers to A. Pointers have built-in operators for ==, <,

Take out the two *s and see what happens.
 
K

Kai-Uwe Bux

Phlip said:
(Tip: always use a typedef for non-trivial templated types.)

That map contains pointers to A. Pointers have built-in operators for ==,
<,

That is not entirely correct: although operator< is syntactically
well-formed for arguments of type A*, this comparison is

(a) only defined for pointers into an array of A, and
(b) not used in the comparison for the map above.

The map uses std::less<>, and std::less< pair<S,T> > is defined in terms of
std::less<S> and std::less<T>. It so happens that the standard requires
std::less<A*> to be well-defined and an ordering for all possible values of
A*. This requirement, however, is totally unrelated to operator< as applied
to A*: there is no guarantee that std::less<A*> will call operator<(A*,A*).


Best

Kai-Uwe Bux
 
A

Andrey Tarasevich

...
I wrote a simple program to learn the usage of STL template
map and set. Although I did not give out any Compare function
with respect to struct A, the program got compiled without
any complain using g++. Could you explain why?

You program does not depend in any way on the comparison function for 'struct
A'. That's why the compiler does not complain.

Your containers use 'std::pair<A*, A*>' values as keys. That's what needs to be
compared. Standard library provides a template that implements comparison
function 'operator <' for 'std::pair<>' specializations. That template will in
turn rely on the 'operator <' for 'A*' values. The latter is built-in in the
language.

If you want your compiler to complain, try using

set< A > haha1;

or

set< pair<A, A> > haha2;

Both will require a comparison function for 'struct A' and, since you didn't
provide one, the compiler will complain.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top