关于C++map的简单使用
C++的map属于C++STL的成员,但不知道为什么,很多的C++程序猿们,对于C++的map都不太使用,而作为小菜菜的我本着对知识的虔诚,对这个知识点进行一些总结,以下是代码和注释:
//简单的电话薄操作实例
#include <iostream>
#include <map>
#include <string>g
using namespace std;
int main(){
map<string, int> mp; //对map进行实例化
int i = 0;
string name;
int tel;
while (i < 3){
cin >> name >> tel;
mp.insert(pair<string, int>(name, tel)); //插入数据操作
i++;
}
map<string, int>::iterator p; //和其他容器一样,map也可以用迭代器来访问
cout << "你输入的数据如下:" << endl;
for (p = mp.begin(); p != mp.end(); p++){ // map容器数据的输出
cout << p->first << p->second << endl;
}
cout << "请输入你要删除的姓名:";
cin >> name;
//map作为一个按照第一个关键字进行索引的有序集合,因此,它的find()的参数是它的第一个索引的值
//在find执行完毕后,若找到这个值,该迭代器就会指向该值,否则,就会等于该map对象的end()
p = mp.find(name);
if (p==mp.end()) cout << "Not found!\n";
else {
// map的删除函数
mp.erase(p);
}
for (p = mp.begin(); p != mp.end(); p++){
cout << p->first << p->second <<endl;
}
return 0;
}
以上就是本人对map的简单用法的总结,若有不足之处,欢迎指出;