介绍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");
}
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » C++ Map元素寻找最近元素
发表评论 取消回复