Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 쌍의 정렬된 벡터에서 이진 검색

<시간/>

이것은 쌍의 정렬된 벡터에서 이진 검색을 구현하는 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