Reputation: 767
I need a container in which i can store a char*
key and int
value.
I can use std::map
and mfc CMap
but i dont know few operation when using char*
as key.
Something like below:
#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;
}
I want to know both the solutions with map
as well as CMap
.
Upvotes: 2
Views: 2632
Reputation: 767
Here is the Example how to use std""map with char* key and 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;
}
By Using MFC cmap also we can achieve the same but the operations might(functions) change.
Upvotes: 2
Reputation: 1570
Be aware that if you don't write your own comparator, stuff that will actually be compared by internal map functions are memory addresses of your char* elements. So, you would basically need your own comparator, which is not that hard to write. Or simply use std::string
as key and whenever you need char*
you just call string.c_str()
.
Upvotes: 1