具有char*键和int值的容器

Container with char* key and int value

本文关键字:int char 键和 具有      更新时间:2023-10-16

我需要一个可以存储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"映射char* key和int value的示例。

//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,我们也可以实现相同的,但操作(函数)可能会改变。

请注意,如果您不编写自己的比较器,则内部映射函数实际比较的东西是char*元素的内存地址。你需要自己的比较器,这并不难写。或者简单地使用std::string作为键,当您需要char*时,只需调用string.c_str()