"Florent Garcin" <> wrote in message
news:...
: I would like to use the map structure with a key of Pair<string, string>
: and an int as the value.
:
: Pair is defined as:
....
: bool operator < (const Pair<T1, T2> p) const
: {
: return !(*this == p) && (first < p.first || (!(p.first < first) &&
: second < p.second));
: }
....
: That means the two pairs of, for instance, strings ("A", "B") and ("B",
: "A") are equals.
Well, this is not what your operator < implies: as it looks through
map elements using a bunary search based on op<, the functions of std::map
will be taken away from the entry being looked for.
But does it make sense for your pair class to accept separate types for
its two elements if the elements are supposed to be interchangeable ??
I don't think so.
: Unfortunately, when I run the following code, I have a strange
behaviour.
....
: Why is it not as expected? Does anyone know what I'm doing wrong?
When std::map does not behave as expected, always check your ordering
function.
If you want the order of the pair's element no not matter,
try something like:
friend bool operator < ( .... a, .... b )
{
T const* a1 = &a.first;
T const* a2 = &a.second;
if( *a2<*a1 ) swap( a1, a2 );
T const* b1 = &b.first;
T const* b2 = &b.second;
if( *b2<*b1 ) swap( b1, b2 );
return (*a1<*b1)||(!(*b1<*a1)&&(*a2<*b2);
}
Or possibly better & easier: keep the two elements of your
pair class ordered at all times ( e.g. swap first & second
if the latter is smaller ).
Amicalement --Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form