【问题标题】:String->Structure CMap字符串->结构 CMap
【发布时间】:2009-05-11 15:06:34
【问题描述】:

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

任何人都可以为此发布示例代码吗?

例如:

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

string1 -> strcut_sample

【问题讨论】:

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


    【解决方案1】:
    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 的更多详细信息。

    【讨论】:

    • 一些参考文献谈到必须编写 HashKey 的实现以使用 CString 作为键。那么这有必要吗?
    【解决方案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 可能会使代码更具可读性。

    【讨论】:

    • 你没有定义“s”。 make_pair("test", s) 不会编译。请更正此问题,以免使正在尝试学习的人感到困惑。
    • 感谢您的回答,但我正在研究 MFC 特定的方法。是的,我也可以接受你的回答。再次感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 2022-12-19
    • 2016-01-05
    • 2014-04-28
    • 2021-01-13
    相关资源
    最近更新 更多