【问题标题】:Container with char* key and int value具有 char* 键和 int 值的容器
【发布时间】:2013-06-08 13:47:32
【问题描述】:

我需要一个容器,我可以在其中存储 char* 键和 int 值。

我可以使用std::map 和mfc CMap,但我不知道使用char* 作为键时的一些操作。

如下所示:

#include"iostream"
#include<map>
using namespace std;

std::map<char*,int>Mymap;
or
//Cmap<char*, char*, int, int>Mymap;

char* p = "AAA";
char* q = "BBB";

int p_val = 10;
int q_val = 20;

int main()
{
    // How to use insert, find and access keys      

    return 0;
}

我想知道mapCMap 的解决方案。

【问题讨论】:

  • 使用std::string 可以省去很多麻烦。 CMap 是什么?似乎不是 C++ 的一部分。
  • CMap 是 mfc http://msdn.microsoft.com/en-us/library/s897094z%28v=vs.80%29.aspx 的一部分 ..我有一个 char* 密钥,所以我需要将密钥转换为 std::stringCstring 如果我要更改密钥?

标签: c++ map mfc stdmap


【解决方案1】:

这里是如何使用带有 char* 键和 int 值的 std""map 的示例。

//Example of std::map with char* key and int as value.

#include"iostream"
using namespace std;
#include<map>

struct cmp_str
{
    bool operator()(char *first, char  *second)
    {
        return strcmp(first, second) < 0;
    }
};

typedef std::map<char*,int, cmp_str>MAP;
MAP myMap;

void Search(char *Key)
{
    MAP::iterator iter = myMap.find(Key);

    if (iter != myMap.end())
    {
        cout<<"Key : "<<(*iter).first<<" found whith value : "<<(*iter).second<<endl;
    }
    else
    {
        cout<<"Key does not found"<<endl;
    }
}

int main()
{
    char *Key1 = "DEV";
    char *Key2 = "TEST";
    char *Key3 = "dev";

    //Insert Key in Map
    myMap.insert(MAP::value_type(Key1, 100));
    myMap.insert(MAP::value_type(Key2, 200));


    // Find Key in Map
    Search(Key1);       // Present in Map
    Search(Key2);       // Present in Map

    Search(Key3);       // Not in Map as it's case sensitive

    myMap.erase(Key2);  // Delete Key2
    Search(Key2);       // Not in Map as deleted 

    return 0;
}

通过使用 MFC cmap 我们也可以实现相同的效果,但操作可能(功能)会发生变化。

【讨论】:

    【解决方案2】:

    请注意,如果您不编写自己的比较器,则内部映射函数实际上会比较的内容是您的 char* 元素的内存地址。因此,您基本上需要自己的比较器,这并不难编写。或者干脆使用std::string 作为键,当您需要char* 时,您只需拨打string.c_str()

    【讨论】:

    • 是的,上面的解释是正确的,但我现在只需要我在答案中发布的 char* 键
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多