C++ 中兩個列表中共同元素的最小索引和
假設兩個人想選擇不同的城市,他們以不同的列表列出了這些城市,我們需要幫助他們找到共同的選擇。因此,我們需要找到他們都標記的那些城市。
此操作與集合交集特性非常相似,我們將兩個列表作為集合,然後執行集合交集以獲取公共元素。
例項
#include <iostream> #include <vector> #include <algorithm> using namespace std; vector<string> commonInterest(string set1[], int n1, string set2[], int n2) { vector<string> v(min(n1, n2)); vector<string>::iterator it; // Sorting both the list sort(set1, set1 + n1); sort(set2, set2 + n2); it = set_intersection(set1, set1 + n1, set2, set2 + n2, v.begin()); return v; } int main() { string first[] = { "Kolkata", "Hyderabad", "Chennai", "Delhi" }; int n1 = sizeof(first) / sizeof(first[0]); string second[] = { "Mumbai", "Kolkata", "Durgapur", "Delhi" }; int n2 = sizeof(second) / sizeof(second[0]); vector<string> v = commonInterest(first, n1, second, n2); cout << "Common cities: "; for (int i = 0; i < v.size(); i++) cout << ' ' << v[i]; cout << endl; }
輸出
Common cities: Delhi Kolkata
廣告