进阶篇_map容器(保存键值对)

来源:互联网 发布:php手册中文版下载 编辑:程序博客网 时间:2024/05/21 09:08

1. 三种向map容器插入数据对的方法(等效)

map<int, Employee> mapEmployee;Employee emp1;mapEmployee.insert(pair<int, Employee>(1, emp1)); //法一插入:使用pair建立员工号1和员工对象emp1的映射关系,并插入map容器中 mapEmployee.insert(map<int, Employee>::value_type(1, emp1)); //法二插入:使用value_type类型实现数据的插入 mapEmployee[1983] = emp1; //法三插入:向map容器中插入一个数据对(1983, emp1) 

2. 根据键找到对应的值

a. 通过迭代器输出数据对的键和值(遍历):

for(map<int, Employee>::iterator it; it!=mapEmployee.end(); ++it){cout<<it->first<<endl; //通过迭代器输出数据对的键和值cout<<it->second.getname()<<endl; }
b.通过 map容器的find()函数查找某一个键(也通过迭代器,这种方式用的更多):

int findkey = 1; //定义要查找的键map<int, Employee>::iterator it = mapEmployee.find(findkey);cout<<it->first<<" "<<it->second.getname()<<endl; 

3. 访问某个范围的数据对


int fromkey = 1;int tokey = 1000; //定义键的范围 map<int, Employee>::iterator itfrom = mapEmployee.lower_bound(fromkey); map<int, Employee>::iterator itto = mapEmployee.upper_bound(tokey);//用迭代器表示起始位置和终止位置for(map<int, Employee>::iterator it = itfrom; it!=itto; ++it){cout<<it->first<<endl; //输出范围内的所有数据} mapEmployee.erase(itfrom, itto);//删除范围内的所有数据
以上代码中,分别使用了lower_bound()与upper_bound()函数来获得指向这个范围的起始位置和终止位置的迭代器

0 0
原创粉丝点击