【发布时间】:2009-05-11 15:06:34
【问题描述】:
我的要求是给定一个字符串作为映射的键,我应该能够检索一个结构。
任何人都可以为此发布示例代码吗?
例如:
struct
{
int a;
int b;
int c;
}struct_sample;
string1 -> strcut_sample
【问题讨论】:
标签: c++ visual-c++ mfc
我的要求是给定一个字符串作为映射的键,我应该能够检索一个结构。
任何人都可以为此发布示例代码吗?
例如:
struct
{
int a;
int b;
int c;
}struct_sample;
string1 -> strcut_sample
【问题讨论】:
标签: c++ visual-c++ mfc
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 的更多详细信息。
【讨论】:
如果你愿意坚持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 可能会使代码更具可读性。
【讨论】: