STL查找算法


      标准模板库提供了一组在有序范围内查找元素的操作。这些函数都是假设,除非将比较函数的对象给定位最后一个参数,否则就使用运算符<。如果将比较函数对象给定位为最后一位参数,该比较对象必须像排序元素那样查找元素。
      如果指定的值出现在排序范围内,Binary_search函数就会返回true。其他算法用于查找同样的排序范围。Lower_bound函数返回指向给定值第一次出现位置的迭代器,upper_bound函数返回指向指定值最后一次出现未知的迭代器。如果没有找到该值,他们都返回容器内最后一个元素的迭代器。函数equal_range返回一对迭代器,分别表示给定值第一次出现和最后一次出现的位置,迭代器在pair类中返回,该类在<utility>中定义。这个类包含一个成员函数make_pair,他用以前定义的类型创建了一对项目,该对中的第一个元素可以使用变量first访问,第二个元素可以使用变量second 访问,注意STL还提供了find find_if 和count操作,来查找无序范围内的元素。但是,这些操作的阶是O(n),而有序范围的查找算法的阶是O(longN)。下面的STL 函数使用向前的迭代器查找元素。

bool binary_search(ForIter first ,ForIter last ,const T &value);
bool binary_search(ForIter first ,ForIter last ,const T &value Compare cmp);//return true if the value appear in the sorted range
//from first to last
//returns false if value id not found
//a compare function objcect may be supplied
ForIter lower_bound(ForIter first ,ForIter last ,const T &value);
ForIter lower_bound(ForIter first ,FOrIter last ,const T &value ,Compare cmp);
//return an iterator pointing to the first occurence of value
//in the sorted range from first to last;
//return last if the value not found
//a compare function object may be supplied
ForIter upper_bound(ForIter first ,ForIter last ,const T&value);
ForIter upper_bound(ForIter first ,ForIter last ,const T &valude,Compare cmp);
//return an iterator pointing to the last occurence of value
//in the sorted range from first to last
//return last fi the value not found
//a compare function object may be supplied
pair<ForIter,ForIter> equal_range(ForIter first,ForIter last ,const T &value);
pair<ForIter,ForIter> equal_range(ForIter first,ForIter last ,const T &value,Compare cmp);
//Combines lower_bound and upper_bound to return a pair
//of iterators to the first and one past the last occurence of
//value.
//both Iterators point to last if value is not found
//A comparion function object may be supplied

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值