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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With