我想一个字符数组值添加到地图中,但上显示字符数组的值不打算来,但显示的整数值。 即ii.first未显示,但ii.second正确显示。添加字符串值映射在C++
这里是我运行的完整代码,
#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();
}
上运行的代码获得的输出:
Enter the employee name
farhan
Enter the employee id
909
Map size: 1
the first=: 909
这里first = farhan:909
,应该是正确的输出,任何人都可以让我了解我在哪里做错了?
使用'std :: string',而不是'const char *'作为键。 –
@RichardHodges,你好先生....我曾尝试过使用字符串,我可以知道使用char *时出现了什么错误。 此外,提及使用的关键是char *而不是const char * ...请验证一次...谢谢... –
@FarhanPatel char *'是用于传统的C代码。 'std :: string'的优点很多(类型安全,自动内存管理,没有缓冲区溢出,为它重载的操作符等等) – bolov