这是如何使用带有 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,我们也可以实现相同的功能,但操作可能(功能)会发生变化。