map::find和map::lower_bound/upper_bound的使用

1.map.find()

用find函数来定位数据出现位置,它返回的一个迭代器,当数据出现时,它返回数据所在位置的迭代器,如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器,函数原型

     iterator find (const key_type& k);
const_iterator find (const key_type& k) const;

实例程序:

// map::find
#include <iostream>
#include <map>

int main ()
{
  std::map<char,int> mymap;
  std::map<char,int>::iterator it;

  mymap['a']=50;
  mymap['b']=100;
  mymap['c']=150;
  mymap['d']=200;

  it = mymap.find('b');
  if (it != mymap.end())
    mymap.erase (it);

  // print content:
  std::cout << "elements in mymap:" << '\n';
  std::cout << "a => " << mymap.find('a')->second << '\n';
  std::cout << "c => " << mymap.find('c')->second << '\n';
  std::cout << "d => " << mymap.find('d')->second << '\n';

  return 0;
}

输出:

elements in mymap:
a => 50
c => 150
d => 200

2.map.lower_bound/upper_bound

map容器是根据键值进行排序的,STL库中的函数原型:

iterator upper_bound (const key_type& k);
const_iterator upper_bound (const key_type& k) const;

iterator lower_bound (const key_type& k);
const_iterator lower_bound (const key_type& k) const;

实例程序:

#include "stdafx.h"
#include <string>
#include <map>
 
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    map<int,string> maptmp;
    map<int,string>::iterator pos,pos1;
    maptmp[1]="a";
    maptmp[2]="b";
    maptmp[4]="c";
    maptmp[3]="f";
    maptmp[5]="d";
    pos = maptmp.lower_bound(3);
    pos1 = maptmp.upper_bound(3);
    printf("lower_bound %d=>%s\n",pos->first,pos->second.c_str());
    printf("upper_bound %d=>%s\n",pos1->first,pos1->second.c_str());
    system("pause");
    return 0;
}

输出:lower_bound 3=>"f"upper_bound 4=>"c"

一句话解释:
lower_bound(k)寻找  k <= ? 并返回其迭代器 
upper_bound(k)寻找 k < ? 并返回其迭代器 
(其中 ?为那个最接近的key值)
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值