使用 C++ 对排序向量进行二分查找

c++server side programmingprogramming

这是一个 C++ 程序,用于在对排序向量中实现二分查找。

算法

Begin
   Declare a structure keycompare.
      Function operator()(const pair& v, const int& k)
      returns Booleans.
         Status = v.first < k.
         Return status.
      Function operator()(const pair& v, const int& k)
      returns Booleans.
         Status = k < v.first.
         Return status.
   Declare a vector v.
   Declare key and value pair within v of the integer datatype.
   Call push_back() function to insert values in v vector.
   Call sort() function to sort all elements of the vector v.
   Print “Sorted vector”.
   Print “Key” “Value”.
   for (pair& n : v)
      print the first and second value of n.
   if (binary_search(v.begin(), v.end(), 50,keycompare())) then
      print “50 exists in vector”.
   Else
      Print “50 does not exist”.
   if (binary_search(v.begin(), v.end(), 7,keycompare() )) then
      print “7 exists in vector”.
   Else
      Print “7 does not exist”.
End.

示例代码

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
struct keycompare {
   bool operator()(const pair<int, int>& v, const int& k) {
      return (v.first < k);
   }
   bool operator()(const int& k, const pair<int, int>& v) {
      return (k < v.first);
   }
};
int main() {
   vector<pair<int, int>> v;
   v.push_back(make_pair(7, 26));
   v.push_back(make_pair(6, 76));
   v.push_back(make_pair(4, 16));
   v.push_back(make_pair(5, 36));
   sort(v.begin(), v.end());
   cout<<"Sorted vector"<<endl;
   cout << "KEY" << '\t' << "VALUE" << endl;
   for (pair& n : v)
      cout << n.first << '\t' << n.second << endl;
   if (binary_search(v.begin(), v.end(), 50,keycompare()))
      cout << "50 exists in vector";
   else
      cout << "50 does not exist";
      cout << endl;
   if (binary_search(v.begin(), v.end(), 7,keycompare() ))
      cout << "7 exists in vector";
   else
      cout << "7 does not exist";
   return 0;
}

输出

Sorted vector
KEY VALUE
4 16
5 36
6 76
7 26
50 does not exist
7 exists in vector

相关文章