views:

681

answers:

2

hi,

My requirement is given a string as key to the map i should be able to retrive a structure.

Can any one please post a sample code for this.

Ex:

struct
{
int a;
int b;
int c;
}struct_sample;

string1 -> strcut_sample

+1  A: 
CMap<CString,LPCTSTR, struct_sample,struct_sample> myMap;

struct_sample aTest;
aTest.a = 1;
aTest.b = 2;
aTest.c = 3;
myMap.SetAt("test",aTest);
...

    struct_sample aLookupTest;
    BOOL bExists = myMap.Lookup("test",aLookupTest); //Retrieves the 
                             //struct_sample corresponding to "test".

Example from MDSN for further details of CMap.

aJ
+2  A: 

If you are willing to stick to MFC, go for the answer of aJ.

Else you're better of with a standard library map. Be sure to check it's documentation - there's a lot to be learned. I usually use http://www.sgi.com/tech/stl/table_of_contents.html.

#include <map>
#include <string>
#include <utility> // for make_pair

using namespace std;

int main() {
    std::map< string, struct_sample > myMap;
    const struct_sample aTest = { 1,2,3 };
    myMap.insert(make_pair( "test", aTest ) );
    myMap[ "test2" ] = aTest; // does a default construction of the mapped struct, first => little slower than the map::insert

    const map<string, struct_sample >::const_iterator aLookupTest = myMap.find( "test" );
    const bool bExists = aLookupTest != myMap.end();

    aLookupTest->second.a = 10;
    myMap[ "test" ].b = 20;

}

Note: using a typedef for the templates may make the code more readable.

xtofl
You didn't define "s". make_pair( "test", s ) will not compile. Please correct this so that it won't confuse people who are trying to learn.
A. Levy
Thanks. 's Been corrected.
xtofl
Thanks for the answer, but i was looking at MFC specific way to do it. Yes, i can go with your answer too. Once again thanks for the answer.
coolcake