Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String->Structure CMap

My requirement is that given a string as key to the map, I should be able to retrieve a structure.

Can anyone please post sample code for this?

Ex:

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

string1 -> strcut_sample

like image 600
coolcake Avatar asked May 11 '09 15:05

coolcake


2 Answers

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.

like image 131
aJ. Avatar answered Oct 02 '22 14:10

aJ.


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.

like image 37
xtofl Avatar answered Oct 02 '22 14:10

xtofl