Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Binary Search ใน Vector ของ Pairs ที่จัดเรียงแล้วใน C++

นี่คือโปรแกรม C++ สำหรับทำ Binary Search ใน vector ของ pairs ที่จัดเรียงแล้ว

อัลกอริทึม

เริ่มต้น
  ประกาศโครงสร้าง keycompare
    ฟังก์ชัน operator()(const pair& v, const int& k) คืนค่า Boolean
      status = v.first < k
      คืนค่า status
    ฟังก์ชัน operator()(const int& k, const pair& v) คืนค่า Boolean
      status = k < v.first
      คืนค่า status
  ประกาศ vector v
  ประกาศ key และ value pair ใน v ชนิด integer
  เรียก push_back() เพื่อแทรกค่าใน v vector
  เรียก sort() เพื่อจัดเรียงสมาชิกทั้งหมดของ vector v
  แสดง "Sorted vector"
  แสดง "Key" "Value"
  for (pair& n : v)
    แสดงค่า first และ second ของ n
  if (binary_search(v.begin(), v.end(), 50, keycompare())) แสดง "50 exists in vector"
  Else แสดง "50 does not exist"
  if (binary_search(v.begin(), v.end(), 7, keycompare())) แสดง "7 exists in vector"
  Else แสดง "7 does not exist"
สิ้นสุด

ตัวอย่างโค้ด

#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