使用 C++ 中的 STL 進行合併運算 | merge()、includes()、set_union()、set_intersection()、set_difference()、inplace_merge


在本教程中,我們將討論一個程式,以瞭解使用 C++ 中的 STL 進行各種合併運算。

merge() 函式用於以新容器也排序的方式合併兩個已排序的容器。此外,includes() 用於檢查第一個容器中的元素是否在第二個容器中。

示例

 即時演示

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main(){
   vector<int> v1 = {1, 3, 4, 5, 20, 30};
   vector<int> v2 = {1, 5, 6, 7, 25, 30};
   //initializing resultant vector
   vector<int> v3(12);
   merge(v1.begin(), v1.end(), v2.begin(),
   v2.end(), v3.begin());
   cout << "The new container after merging is :\n";
   for (int &x : v3)
      cout << x << " ";
   cout << endl;
   vector<int> v4 = {1, 3, 4, 5, 6, 20, 25, 30};
   includes(v4.begin(), v4.end(), v1.begin(), v1.end())?
      cout << "v4 includes v1":
      cout << "v4 does'nt include v1";
   return 0;
}

輸出

The new container after merging is :
1 1 3 4 5 5 6 7 20 25 30 30
v4 includes v1

更新於: 14-4-2020

107 次瀏覽

啟動你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.