📜  对排序向量中的二进制搜索

📅  最后修改于: 2021-05-30 17:47:20             🧑  作者: Mango

给定向量按其第一个值(键)排序时,如何将STL binary_search应用于向量对(键,值)

代码中的struct compare包含两个将键(搜索元素)与向量中的第一个元素进行比较的函数

/* C++ code to demonstrate how Binary Search
   can be applied on a vector of pairs */
#include 
using namespace std;
  
struct compare {
    bool operator()(const pair& value, 
                                const int& key)
    {
        return (value.first < key);
    }
    bool operator()(const int& key, 
                    const pair& value)
    {
        return (key < value.first);
    }
};
  
int main()
{
    // initializing the vector of pairs
    vector > vect;
  
    // insertion of pairs (key, value) in vector vect
    vect.push_back(make_pair(1, 20));
    vect.push_back(make_pair(3, 42));
    vect.push_back(make_pair(4, 36));
    vect.push_back(make_pair(2, 80));
    vect.push_back(make_pair(7, 50));
    vect.push_back(make_pair(9, 20));
    vect.push_back(make_pair(3, 29));
  
    // sorting the vector according to key
    sort(vect.begin(), vect.end());
  
    // printing the sorted vector
    cout << "KEY" << '\t' << "ELEMENT" << endl;
    for (pair& x : vect)
        cout << x.first << '\t' << x.second << endl;
  
    // searching for the key element 3
    cout << "search for key 3 in vector" << endl;
    if (binary_search(vect.begin(), vect.end(),
                                  3, compare()))
        cout << "Element found";
    else
        cout << "Element not found";
  
    return 0;
}
输出:
KEY    ELEMENT
1    20
2    80
3    29
3    42
4    36
7    50
9    20
search for key 3 in vector
Element found

上面的binary_search操作具有时间复杂度O(lg n)

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”