STL 容器 map/multimap的查找&迭代器

map/multimap的查找

(1)map.find(key); 查找键key是否存在,若存在,返回该键的元素的迭代器;若不存在,返回map.end();

(2)map.count(key); //返回容器中键值为key的对组个数。对map来说,要么是0,要么是1;对multimap来说,值>=0。

(3)map.lower_bound(keyElem); //返回第一个key>=keyElem元素的迭代器。

(4)map.upper_bound(keyElem); // 返回第一个key>keyElem元素的迭代器。

(5)map.equal_range(keyElem); //返回容器中key与keyElem相等的上下限的两个迭代器。上限是闭区间,下限是开区间,如 [beg,end) 。

例子:

#include <iostream>
#include <functional>
#include <algorithm>
#include <map>
#include <string>

using namespace std;

int main()
{
	//map
	map<int, string> mapStu;
	mapStu.insert(pair<int, string>(2, "李四"));
	mapStu.insert(pair<int, string>(1, "张三"));
	mapStu.insert(pair<int, string>(3, "王五"));
	mapStu.insert(pair<int, string>(4, "赵六"));


	//multimap
	multimap<int, string> mmapTeacher; //<班级, 老师姓名>
	mmapTeacher.insert(pair<int, string>(101, "李老师"));
	mmapTeacher.insert(pair<int, string>(101, "张老师"));
	mmapTeacher.insert(pair<int, string>(102, "王老师"));
	mmapTeacher.insert(pair<int, string>(102, "赵老师"));


	//map 的查找
	map<int, string>::iterator it = mapStu.find(3);
	if(it != mapStu.end()) //找到了
	{
		cout<<"mapStu.find(3) = "<<(*it).second<<endl;
	}else{ //没找到
		cout<<"找不到键值为3的键值对! "<<endl;
	}


	//multimap 的查找
	int count = mmapTeacher.count(101);
	multimap<int, string>::iterator mit = mmapTeacher.find(101);
	if(mit != mmapTeacher.end()) //找到了
	{
		//输出multimp 中的同一键的多个值
		//方法一 通过比较key, 循环判断(推荐使用, 第一种: 效率好, 更灵活)
		for(mmapTeacher.begin(); mit != mmapTeacher.end(); mit++)
		{
			if((*mit).first == 101)
			{
			    cout<<"mmapTeacher.find(101) = "<<(*mit).second<<endl;
			}else
			{
				break;
			}
		}

		//方法二 通过count计数来控制
		/*for(int i = 0; i < count; i++, mit++)
		{
			cout<<"mmapTeacher.find(101) = "<<(*mit).second<<endl;
		}*/

	}else //没找到
	{
		cout<<"找不到键值为101的键值对! "<<endl;
	}



	//equal_range 用法
	pair<multimap<int, string>::iterator ,multimap<int, string>::iterator> mmiit = mmapTeacher.equal_range(101);
	
	//第一个迭代器, 对应begin
	if(mmiit.first != mmapTeacher.end())
	{
	    cout<<"mmapTeacher.equal_range(101).begin = "<<(*mmiit.first).second<<endl;
	}
	//第二个迭代器, 对应end
	if(mmiit.second != mmapTeacher.end())
	{
	    cout<<"mmapTeacher.equal_range(101).end = "<<(*mmiit.second).second<<endl;
	}
	
	system("pause");
	return 0;
}

运行环境: vc++ 2010学习版
运行结果:
在这里插入图片描述

发布了35 篇原创文章 · 获赞 33 · 访问量 300

猜你喜欢

转载自blog.csdn.net/m0_45867846/article/details/105474384