C++map映射的插入和输出
当我想要实现map的插入的时候,可以使用一下三种方法:
使用pair的方式:
//使用pair进行插入
mp.insert(pair<string,int>("God rewards the diligent",1));
使用value_type 的方式
//使用value_type进行插入
mp.insert(map<string,int>::value_type("New opportunities and challenge in the next",2));
使用数组的方式
//使用数组进行插入
mp["Hardworking"]=3;
当然我们也可以在定义的时候对其进行初始化,听说链表也可以,不过我的编译器版本是2010,版本太低了不支持。
然后我是用迭代器的方式进行输出:
// 利用迭代器实现输出
for(map<string,int>::iterator it=mp.begin();it!=mp.end();it++){
cout<<it->first<<" "<<it->second<<endl;
}
结果显示正常,但是这是我是用c++输出流显示的输出,当我想使用c中的printf()的时候,却只输出了乱码。
//利用迭代器实现输出
for(map<string,int>::iterator it=mp.begin();it!=mp.end();it++){
cout<<it->first<<" "<<it->second<<endl;
}
//利用c中的printf()进行输出
for(map<string,int>::iterator it=mp.begin();it!=mp.end();it++){
printf("%s %d\n",it->first,it->second);
}
结果截图:
后来发现,原来c中的printf()想要输出字符串,需要知道该字符串的首地址才能输出,我上边的代码,引用c_str()成员方法便可以了返回该字符串的首地址了。
//利用c中的printf()进行输出
for(map<string,int>::iterator it=mp.begin();it!=mp.end();it++){
printf("%s %d\n",it->first.c_str(),it->second);
}
这样便可以输出正确了。