
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Example
#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; }
Output
Common cities: Delhi Kolkata
Advertisements