String->结构CMap

时间:2009-05-11 15:06:34

标签: c++ visual-c++ mfc

我的要求是,给定一个字符串作为地图的关键,我应该能够检索一个结构。

有人可以为此发贴示例代码吗?

例如:

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

string1 - > strcut_sample

2 个答案:

答案 0 :(得分:6)

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

来自MDSN的示例,了解CMap的更多详细信息。

答案 1 :(得分:2)

如果您愿意坚持使用MFC,请转到aJ的答案。

否则,您最好使用标准库地图。一定要查看它的文档 - 有很多东西需要学习。我通常使用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;

}

注意:对模板使用typedef可能会使代码更具可读性。