介绍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");
	}
	

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部