Minimum Index Sum for Common Elements of Two Lists in C++

Suppose two person wants to choose different cities, they have listed out the cities in different list, we have to help the, to find common choices. So we need to find those cities, those are marked by both of them.

This operation is very similar to the set intersection property, we will take two lists as set, then perform the set intersection to get the common elements.


 Live Demo

#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,
   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