As Richard mentioned in comment, intersection can be done easily with std::set_intersection()
. The pre-condition are sorted containers.
Thereby, the "set" in set_intersection()
could be understood rather in a mathematical sense – it is not limited to std::set
. A sorted std::vector
can be used as well.
To sort a std::vector
, std::sort()
can be used. In this case, the pre-condition is a possible order of elements i.e. the operator<
is defined for the element type.
QPair
defines an operator<
which can be used if the types of first
and second
do as well.
As the OP didn't mention which types are QPair
ed, I chose std::string
and double
for my sample isectQPair.cc
:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <QtCore>
int main()
{
// prepare sample data
typedef QPair<std::string, double> Pair;
Pair
a("Hello", 1.23),
b("World", 2.34),
c("Stack", 3.45),
d("Overflow", 4.56),
e("C++11", 5.67),
f("C++14", 6.78),
g("C++17", 7.89),
h("C++20", 8.90),
i("gin hill", 10.1),
j("scheff", 0.0);
std::vector<Pair> vec1({ a, b });
std::vector<Pair> vec2({ c, d, a, e, h });
std::vector<Pair> vec3({ i, j, a });
// sort vectors
std::sort(vec1.begin(), vec1.end());
std::sort(vec2.begin(), vec2.end());
std::sort(vec3.begin(), vec3.end());
// intersect vectors
std::vector<Pair> isect12;
std::set_intersection(
vec1.begin(), vec1.end(), vec2.begin(), vec2.end(),
std::back_inserter(isect12));
std::vector<Pair> isect123;
std::set_intersection(
isect12.begin(), isect12.end(), vec3.begin(), vec3.end(),
std::back_inserter(isect123));
// report
const size_t n = isect123.size();
std::cout << "Intersection contains " << n << " elements"
<< (n ? ':' : '.') << '\n';
for (size_t i = 0; i < n; ++i) {
const Pair &entry = isect123[i];
std::cout << (i + 1) << ".: '" << entry.first
<< "', " << entry.second << '\n';
}
// done
return 0;
}
isectQPair.pro
:
SOURCES = isectQPair.cc
Qt = core
Compiled and tested on cygwin on Windows 10:
$ qmake-qt5 isectQPair.pro
$ make
$ ./isectQPair
Intersection contains 1 elements:
1.: 'Hello', 1.23
$
Live Demo on ideone (QPair
replaced with std::pair
)
Another nice Q/A concerning intersection can be found here: SO: how to find the intersection of two std::set in C++?.