C++标准库中的查找函数之有序区间的函数

2014-11-24 11:29:05 · 作者: · 浏览: 0

地点:基地

时间:2014.04.01

--------------------------------------------------------------------------

一、概述

用于有序区间的函数有一下三个,每种方法都使用了两个指针first和last,用于限制元素的域为 [first,last),注意这里是半开半闭区间,且这些元素按从小到大的顺序排序。

1. bool binary_search(Iterator first,Iterator last,const Item& target);

二分查找目标元素。

Iterator lower_bound(Iterator first,Iterator last,const Item& targrt);

返回的指针指向目标出现在域[first,last)中的指针。如果目标不存在则返回的指针指向第一个比目标大的元素。若果数组的元素都小于目标则返回一个与last指针相等的值。可以看做是可以插入到数列且仍保持数列有序的最左边的位置。

Iterator upper_bound(Iterator first,Iterator last,const Item&target);

返回的指针指向第一个比目标大的元素,如数组中没有则返回last指针。可以看成是在目标元素可以插入到数列且保持数列有序的最右的位置。

--------------------------------------------------------------------------

二、实例:

#include
  
   
#include
   
     #include
    
      #include
     
       using namespace std; int main(){ vector
      
        pets; pets.push_back("cat"); pets.push_back("dog"); pets.push_back("fish"); pets.push_back("snake"); pets.push_back("turtle"); vector
       
        ::iterator first_dog = lower_bound(pets.begin(), pets.end(), "dog"); vector
        
         ::iterator after_dog = upper_bound(pets.begin(), pets.end(), "dog"); cout << "lower_bound return value: " << *first_dog << endl; cout << "upper_bound return value: " << *after_dog << endl; return 0; }
        
       
      
     
    
   
  
另外总结一点:当且仅当目标没有出现在目标域中时,lower_bound和upper_bound才会返回相同的指针,这些函数都使用了二叉查找,运行时间都是对数级的。