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

ค้นหาส่วนเสริมสัมพัทธ์ของสองอาร์เรย์ที่จัดเรียงใน C ++


สมมติว่าเรามีอาร์เรย์ที่จัดเรียงสองตัว arr1 และ arr2 มีขนาด m และ n ตามลำดับ เราต้องหาส่วนเสริมสัมพัทธ์ของสองอาร์เรย์ หมายความว่าเราจำเป็นต้องค้นหาองค์ประกอบทั้งหมดที่มีอยู่ใน arr1 แต่ไม่ใช่ใน arr2 ดังนั้นหากอาร์เรย์เป็นแบบ A =[3, 6, 10, 12, 15] และ B =[1, 3, 5, 10, 16] ผลลัพธ์จะเป็น [6, 12, 15]

เพื่อแก้ปัญหานี้ เราสามารถใช้ฟังก์ชัน set_difference เนื่องจากปัญหาคือการตั้งค่าการทำงานที่แตกต่างกันโดยทั่วไป

ตัวอย่าง

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main() {
   int first[] = {3, 6, 10, 12, 15};
   int second[] = {1, 3, 5, 10, 16};
   int n = sizeof(first) / sizeof(first[0]);
   vector<int> temp(5);
   vector<int>::iterator it, ls;
   sort(first, first + 5);
   sort(second, second + 5);
   cout << "First array :";
   for (int i = 0; i < n; i++)
      cout << " " << first[i];
   cout << endl;
   cout << "Second array :";
   for (int i = 0; i < n; i++)
      cout << " " << second[i];
   cout << endl;
   ls = set_difference(first, first + 5, second, second + 5, temp.begin());
   cout << "The result of relative complement ";
   for (it = temp.begin(); it < ls; ++it)
      cout << " " << *it;
   cout << endl;
}

ผลลัพธ์

First array : 3 6 10 12 15
Second array : 1 3 5 10 16
The result of relative complement 6 12 15