我想一個字符數組值添加到地圖中,但上顯示字符數組的值不打算來,但顯示的整數值。 即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