用现成函数进行二分查找

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函数进行排序,然后得到所需元素下标

常用的用法:

查找某个元素可以这样查找

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int n;
    int a[] = {0,2,32,45,344,76756,2345,-123,4323,12321,323,434};

    sort(a, a+12);

    for(int i = 0 ;  i < 12 ; i++)
    {
        cout << a[i] <<" ";
    }
    cout << endl;
    while(cin >> n)
    {
        cout << " lower_index " << lower_bound(a,a+12,n) - a << endl;
        cout << " upper_bound " << upper_bound(a,a+12,n) - a << endl;
        cout << " cha "  << upper_bound(a,a+12,n) - lower_bound(a,a+12,n) << endl;
    }
    return 0;
}

如果找到这个元素那么cha为1否则为0

 

posted @ 2017-07-17 12:43  pprp  阅读(176)  评论(0编辑  收藏  举报