- Trier les vecteurs. Utilisez
std::set_intersection()
trois fois (autant de vecteurs que vous avez - 1).
Temps de complexité Analyse:
- 4 * O (nlogn) = O (nlogn)
- linéaire 2 * (firstSize + secondSize) - 1
- linéaire 2 * (firstSecondInterSize + thirdSize) - 1
- linéaire en 2 * (firstSecondThirdInterSize + fourthSize) - 1
qui est délimitée par O (nlogn), ce qui signifie que le tri est le goulot d'étranglement de l'algorithme.
exemple de code complet:
#include <iostream> // std::cout
#include <algorithm> // std::set_intersection, std::sort
#include <vector> // std::vector
int main() {
std::vector<int> first = {5,10,15,20,25};
std::vector<int> second = {50,40,30,20,10};
std::vector<int> third = {10,20,3,4,0};
std::vector<int> fourth = {4,20,10,3,6};
std::vector<int> v(first.size() + second.size() + third.size() + fourth.size());
std::vector<int>::iterator it;
std::sort (first.begin(),first.end());
std::sort (second.begin(),second.end());
std::sort (third.begin(),third.end());
std::sort (fourth.begin(),fourth.end());
it=std::set_intersection (first.begin(), first.end(), second.begin(), second.end(), v.begin());
it=std::set_intersection (v.begin(), v.end(), third.begin(), third.end(), v.begin());
it=std::set_intersection (v.begin(), v.end(), fourth.begin(), fourth.end(), v.begin());
v.resize(it-v.begin());
std::cout << "The intersection has " << (v.size()) << " elements: ";
for (it=v.begin(); it!=v.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
Sortie:
L'intersection a 2 éléments: 10 20
Peut-être regarder dans [ 'std :: set_intersection'] (http://fr.cppreference.com/w/cpp/algorithm/set_intersection) – Mark
Puisque vous avez plus de deux, [this] (https: //stackoverflow.com/questions/12875993/efficient-set-intersection-of-a-collection-of-sets-in-c) est probablement plus pertinent. – Mark