A Map with both key and value as Struct

Discussion in 'C' started by karthikchinta, Feb 3, 2009.

  1. karthikchinta

    karthikchinta New Member

    Feb 3, 2009
    Likes Received:
    Trophy Points:

    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:


    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...............

  2. xpi0t0s

    xpi0t0s Mentor

    Aug 6, 2004
    Likes Received:
    Trophy Points:
    Senior Support Engineer

    "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).

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice