map key issue - please support

Wilson Wilson@WSSPL.com
Tue Sep 3 00:13:00 GMT 2002



Hi,
Im trying to create an STL map with multiple keys. But the following
implementation fails to search. It returns 'Found' for a set of value which
is not in the map. Please support.

#include <iostream.h>
#include <map>

typedef struct _MapKey
{
    int key1;
    int key2;
} MapKey;

struct ltstr
{
    bool
    operator() ( const MapKey& k1, const MapKey& k2 ) const
    {
        cout << "() operator" << endl;
        cout << k1.key1 << " : " << k1.key2 << " ;; "
                << k2.key1 << " : " << k2.key2 << endl;
        if ( k1.key1 <= k2.key1 )
        {
            if ( k1.key2 < k2.key2 )
            {
                return true;
            }
            return false;
        }
        if ( k1.key2 <= k2.key2 )
        {
            if ( k1.key1 < k2.key1 )
            {
                return true;
            }
            return false;
        }
        return false;
    }
};

typedef map< MapKey, int, ltstr > DataMap;

int
main( void )
{
    MapKey mapKey;
    DataMap dataMap;
    mapKey.key1 = 1;
    mapKey.key2 = 1;
    dataMap[ mapKey ] = 999;
    mapKey.key1 = 1;
    mapKey.key2 = 2;
    dataMap[ mapKey ] = 888;

    mapKey.key1 = 2;
    mapKey.key2 = 2;
    cout << "Searching..." << endl;
    DataMap :: iterator iter = dataMap.find( mapKey );
    if ( iter == dataMap.end() )
    {
        cout << "Not found!" << endl;
    }
    else
    {
        cout << "Found!" << endl;
        cout << "Value = " << ( *iter ).second << endl;
						// Shown as 888, why?
    }

    return 0;
}

Regards

Wilson K J
WebSpectrum Software Pvt Ltd
http://www.wsspl.com
==================================================




More information about the Gcc-help mailing list