码迷,mamicode.com
首页 > 其他好文 > 详细

用现成函数进行二分查找

时间:2017-07-17 13:11:59      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:color   cout   ast   i++   target   位置   需要   函数   out   

2017-07-17 12:00:12

writer:pprp

题目:找到你想要的数的

代码如下:

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
      //test
      int n  ;
      int a[10000];
      cin >> n ;

      for(int i = 0 ; i < n ; i ++)
      {
            cin >> a[i];
      }

      sort(a,a+n);

      for(int i = 0 ; i < n ; i++)
      {
            cout << a[i] << endl;
      }
      int x;

      unique(a,a+n);

      cin >> x;
      cout << lower_bound(a,a+n,x)-a +1<< endl;

    return 0;
}

lower_bound()返回一个 iterator 它指向在[first,last)标记的有序序列中可以插入value,而不会破坏容器顺序的第一个位置,而这个位置标记了一个不小于value 的值。该函数为C++ STL内的函数。

所以如果需要取得某元素下标,需要先用sort函数进行排序,然后得到所需元素下标

用现成函数进行二分查找

标签:color   cout   ast   i++   target   位置   需要   函数   out   

原文地址:http://www.cnblogs.com/ilovelianghui/p/7193726.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!