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; //对列表进行排序 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