Effective STL 學習筆記 Item 34: 瞭解哪些算法但願輸入有序數據

有些個算法對有序的和無序的數據都能應用,但多數狀況下,他們在輸入數據有序時才最有用。 css

下列算法要求輸入數據必須有序: java

  • binary_search, upper_bound, lower_bound, equal_range

    這些算法均使用了二分查找 (binary_search) 以期達到 logarithmic-time lookups,要求數據必須有序。 ios

  • set_union, set_intersection, set_difference, set_symmeteric_difference

    這些算法要求保證時間複雜度爲線性,因此輸入數據必須有序。 c++

  • merge, inplace_merge

    這兩個算法內部使用 merge sort 來完成運算且要求線性時間,也要求輸入必須有序。 算法

  • includes

    也要求線性時間,輸入須有序。 sql

下列算法要求對數據順序無強制要求,但最好有序: shell

  • unique
  • unique_copy

STL 容許咱們本身定義排序算法,爲了讓程序正確的運行,咱們必須保證排序時候所用的比較算法和上述的算法中使用的比較算法相同,例以下面的例子中: bash

vector<int> v;
//...  putting values to this vector.

sort(v.begin(), v.end(), greater<int>); // Sorted in descending order.

bool a4Exists =
        binary_search(v.begin(), v.end(), 5); // Assumes vector sorted in ascending range

試圖從降序排列的數據中按照升序算法去找一個數據,頗有可能會出問題,而下面的表達式中,在 binary_search 中指定比較算法爲排序算法中所使用的比較算法,則沒有問題: dom

bool ret = binary_search(v.begin(), v.end(), 5, greater<int>());

下面是完成的測試代碼: post

#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

#define N       100

#define show(s,m) cout<< m ;if (s) { cout << " 5 exists!" << endl; } else { cout << " 5  not existed!" << endl; }


int main(int argc, char *argv[])
{
    srand(time(NULL));
    vector<int> v(N);
    for (int i = 0; i < N; ++i)
    {
        v[i] = i;
    }

    random_shuffle(v.begin(), v.end());

    sort(v.begin(), v.end(), greater<int>());

    bool ret = binary_search(v.begin(), v.end(), 5);
    show(ret, "Searching in different compare function:");

    ret=binary_search(v.begin(), v.end(), 5, greater<int>());
    show(ret, "Searching in same compare function:");
    return 0;
}

下面是輸出:

Welcome to the Emacs shell

~/Documents/MetaWebBlog/org $ ~/tmp $ ./test
Searching in different compare function:5  not existed!
Searching in same compare function:5 exists!
相關文章
相關標籤/搜索