C++ Map元素寻找最近元素

介绍map元素比较的方法

find方法

功能:查找map中最相等的key
样例:

	std::map<double, string> mapS;
	mapS[1] = std::string("student_1");
	mapS[2] = std::string("student_2");
	mapS[2.2] = std::string("student_2.2");
	mapS[2.8] = std::string("student_2.8");
	mapS[3] = std::string("student_3");

	std::map<double, string>::iterator iter;
	double Key = 1;
	if (mapS.find(Key) != mapS.end())
	{
		printf("Key:%lf\n", Key);
	}

upper_bound方法

功能:寻找第一个大于k的元素
注意:如果查找的Key值大于map中最大的值,则返回end()迭代器
样例:

	std::map<double, string> mapS;
	mapS[1] = std::string("student_1");
	mapS[2] = std::string("student_2");
	mapS[2.2] = std::string("student_2.2");
	mapS[2.8] = std::string("student_2.8");
	mapS[3] = std::string("student_3");
	
	Key = 0.1;
	//Key = 3;
	//Key = 4.1;
	auto iterUp = mapS.upper_bound(Key);//寻找最近大于Key的迭代器
	if (iterUp != mapS.end())
	{
		cout << mapS[iterUp->first] << endl;
	}
	else
	{
		printf("upper_bound Not found element!\n");
	}

lower_bound方法

功能:寻找第一个大于等于k的元素
注意:如果查找的Key值大于map中最大的值,则返回end()迭代器

std::max_element方法

功能:查找map或者vector的最大元素

	std::map<double, string> mapS;
	mapS[1] = std::string("student_1");
	mapS[2] = std::string("student_2");
	mapS[2.2] = std::string("student_2.2");
	mapS[2.8] = std::string("student_2.8");
	mapS[3] = std::string("student_3");
	auto Value = std::max_element(mapS.begin(), mapS.end());

先找相等的值,再向上查找,向上查找返回end则直接查找最大值,返回最大值

总测试代码

	//测试======================================================
	std::map<double, string> mapS;

	mapS[1] = std::string("student_1");
	mapS[2] = std::string("student_2");
	mapS[2.2] = std::string("student_2.2");
	mapS[2.8] = std::string("student_2.8");
	mapS[3] = std::string("student_3");

	std::map<int, string>::iterator iter;

	//iter = mapS.find(1);
	double Key = 1;
	if (mapS.find(Key) != mapS.end())
	{
		//return Key;
		printf("Key:%lf\n", Key);
	}
	//======================================================
	Key = 2.1;
	if (mapS.find(Key) != mapS.end())
	{
		//return Key;
		printf("Key:%lf\n", Key);
	}
	auto iterUp = mapS.upper_bound(Key);
	cout << mapS[iterUp->first] << endl;
	//======================================================
	auto Value = std::max_element(mapS.begin(), mapS.end());


	Key = 0.1;
	//Key = 3;
	//Key = 4.1;
	if (mapS.find(Key) != mapS.end())
	{
		//return Key;
		printf("Key:%lf\n", Key);
	}
	iterUp = mapS.upper_bound(Key);//寻找最近大于Key的迭代器
	if (iterUp != mapS.end())
	{
		cout << mapS[iterUp->first] << endl;
	}
	else
	{
		printf("upper_bound Not found element!\n");
	}
	
	//===========================
	iterUp = mapS.lower_bound(Key);//寻找最近大于等于Key的迭代器
	if (iterUp != mapS.end())
	{
		cout << mapS[iterUp->first] << endl;
	}
	else
	{
		printf("lower_bound Not found element!\n");
	}
	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值