I am trying to add a char array value into a map, but on displaying the value of char array is not coming, however the integer value is displayed. That is ii.first is not displayed, however ii.second is displayed correctly.
Here is the complete code which I am running,
#include <iostream>
#include <cstring>
#include <map>
#include <utility>
using namespace std;
class map_demo {
public:
class cmp_str {
public:
bool operator() (char const *a, char const *b) {
return std::strcmp(a, b) <0;
}
};
private:
typedef map <char*, int, cmp_str> ptype;
ptype p;
public:
void set_value() {
char name[20];
int empid;
cout<<"Enter the employee name\n";
cin.getline(name,20);
// cout<<"name entered=:"<<name;
cout<<"Enter the employee id\n";
cin>>empid;
this->p.insert(map<char *,int>::value_type(name,empid));
}
void get_value() {
cout << "Map size: " << p.size() << endl;
for(ptype::iterator ii=p.begin(); ii!=p.end(); ++ii) {
cout <<"the first="<< (*ii).first << ": " << (*ii).second << endl;
}
}
};
//=====================================================================
int main() {
map_demo mp1;
mp1.set_value();
mp1.get_value();
}
The output obtained on running the code:
Enter the employee name
farhan
Enter the employee id
909
Map size: 1
the first=: 909
Here the first = farhan:909, should be the correct output, can anyone make me understand where I am making it wrong??
std::string, notconst char*for the key.char *is for legacy C-code. The advantages ofstd::stringover it are numerous (type safety, automatic memory management, no buffer overflows, overloaded operators for it, etc etc)p.insert(std::make_pair(name,empid));