Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   A Map with both key and value as Struct (http://www.go4expert.com/forums/map-key-value-struct-t16052/)

karthikchinta 3Feb2009 23:07

A Map with both key and value as Struct
 
Hi,

I am trying to develop one requirement wherein I need a C++ map having both Key and Value as Structures.

The structures are as follows:

typedef struct _keyInfo
{
int Key1;
int Key2;
} T_KeyInfo, * T_pKeyInfo;

typedef struct _valueInfo
{
int value1;
int value2;
int value3;
} T_ValueInfo, * T_pValueInfo;

and my map is:

typedef map<T_pKeyInfo, T_pValueInfo> T_Map, * T_pMap;

I tried to insert one row into this map using the insert command:

M_pMap->insert(T_Map::value_type(L_pKey,L_pValue));

and Later I am trying to retrive the stored values in the map using find command

T_Map::iterator L_iterator;
T_pKeyInfo L_pKey = NULL;
T_pValueInfo L_pValue = NULL;

L_iterator = M_pMap->find(T_Map::key_type(L_pKey));
if (L_iterator != M_pMap->end())
{
L_pValue = L_iterator->second;
int P_Result=L_pValue->value1;
}

Somehow I am not able to retrive the value1 from the map using the above code.

Can anyone please help me in resolving this issue.
It will be OK, if any better approach/procedure exists to have a map with key and value as structs.

Thanks in advance...............


karthik

xpi0t0s 3Feb2009 23:39

Re: A Map with both key and value as Struct
 
http://www.cplusplus.com/reference/stl/map

"Internally, the elements in the map are sorted from lower to higher key value"
So you need to define the Compare class for this to work, which takes two key values and returns a bool indicating which is greater.
If the concept of one T_KeyInfo being greater than another doesn't make sense (for example, which of (0,1) and (1,0) is greater?), then most likely you'd be better off using an unordered list.

Probably what's happening is that the search ends when the default "less than" operator finds a key that is greater than the one specified, and that "less than" is not doing what you expect, which could be that it is considering a T_KeyInfo to have the numeric value Key1 * 2^(8*sizeof(int)) + Key2, which would mean the keys (0,0), (0,1), (0,1000), (1,0) are in order, because (1,0)>(0,1000).


All times are GMT +5.5. The time now is 10:17.