【发布时间】:2016-01-21 10:55:31
【问题描述】:
我正在尝试将 char 数组值添加到地图中,但在显示 char 数组的值时不会出现,但会显示整数值。 即 ii.first 没有显示,但是 ii.second 显示正确。
这是我正在运行的完整代码,
#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相对于它的优点很多(类型安全、自动内存管理、没有缓冲区溢出、它的重载运算符等) -
Char * 不会为您管理内存。所以输入的第二个名称将覆盖第一个(您的地图将字符串的地址存储为键,而不是键本身)
-
看看std::make_pair,用起来更方便。例如
p.insert(std::make_pair(name,empid));
标签: c++ dictionary containers