Many-sets intersection

#include <iostream> #include <algorithm> #include <vector> #include <random> using namespace std; int randint(int min, int max) { random_device rd; // initialize seed once mt19937 rng(rd()); // choose Mersenne-Twister uniform_int_distribution<int> uni(min, max); // guaranteed unbiased return uni(rng); } bool element_in_sequence(vector<int> v, int el) { for (size_t i = 0; i < v.size(); i++) { if (v[i] == el) { return true; } } return false; } vector<vector<int>> generate_sets(int sets, int items, int min_item, int max_item) { vector<vector<int>> all(sets, vector<int>(items)); vector<int> vset; for(size_t k = 0; k < all.size(); k++) { vset = all[k]; for(int j = 0; j < items; j++) { vset.push_back(randint(min_item, max_item)); } sort(vset.begin(), vset.end()); all[k] = vset; } return all; } vector<int> many_sets_intersection(vector<vector<int>> all_sets) { vector<int> first, second, res, checked, intersections; int sets_size = all_sets.size(); for(int i = 1; i < sets_size; i++) { first = all_sets[i-1]; second = all_sets[i]; set_intersection( first.begin(), first.end(), second.begin(), second.end(), back_inserter(intersections) ); } for(const int item : intersections) { if(!element_in_sequence(checked, item)) { int c = count(intersections.begin(), intersections.end(), item); if(c == sets_size - 1) { res.push_back(item); } checked.push_back(item); } } return res; } void show_items(vector<int> items) { for(const int item : items) { cout << item << ' '; } } int main() { int sets = 5, items = 1000, min_item = -1000, max_item = 1000; vector<vector<int>> all = generate_sets(sets, items, min_item, max_item); vector<int> intersection = many_sets_intersection(all); show_items(intersection); /* -983 -971 -896 -796 -715 -713 -708 -471 -339 -269 -255 -245 -92 17 97 151 310 354 378 475 588 614 653 769 967 999 -859 -227 640 */ return 0; }