map::lower_bound/upper_bound的使用

来源:互联网 发布:诸葛亮马前课时辰算法 编辑:程序博客网 时间:2024/05/22 12:15

如题,原来会这两个函数的用法的,但是后来又忘了,这说明,我的理解还不够,所以我今天又折腾了一下

首先看一下函数原型:

[cpp] view plain copy
 print?
  1. iterator upper_bound (const key_type& k);  
  2. const_iterator upper_bound (const key_type& k) const;  

类似的

[cpp] view plain copy
 print?
  1. iterator lower_bound (const key_type& k);  
  2. const_iterator lower_bound (const key_type& k) const;  

看一个例子:

[cpp] view plain copy
 print?
  1. // map::lower_bound/upper_bound  
  2. #include <iostream>  
  3. #include <map>  
  4.   
  5. int main ()  
  6. {  
  7.   std::map<char,int> mymap;  
  8.   std::map<char,int>::iterator itlow,itup;  
  9.   
  10.   mymap['a']=20;  
  11.   mymap['b']=40;   //注释看看  
  12.   mymap['c']=60;  
  13.   mymap['d']=80;  
  14.   mymap['e']=100;  
  15.   
  16.   itlow=mymap.lower_bound ('b');  // 寻找 'b' <= ?  
  17.   itup=mymap.upper_bound ('d');   // 寻找 'c' < ?  
  18.   
  19.   mymap.erase(itlow,itup);        // erases [itlow,itup)  
  20.   
  21.   // print content:  
  22.   for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)  
  23.     std::cout << it->first << " => " << it->second << '\n';  
  24.   
  25.   
  26.   
  27.   return 0;  
  28. }  

输出:

[cpp] view plain copy
 print?
  1. a => 20  
  2. e => 100  

好了,相信看了程序之后就一目了然,但是要怎么记住呢?

一句话解释:

lower_bound(k)寻找  k <= ? 并返回其迭代器 

upper_bound(k)寻找 k < ? 并返回其迭代器 

(其中 ?为那个最接近的key值)

0 0
原创粉丝点击