I want to compare elements of vectors filled with integers to look if for elements with same values (and count them).
So for example, if a[i]==x
, is there a b[j]==x
?
The first implementation that came to mind, is the most simple one of course:
for (int i=0; i < a.size(); i++) {
for (int j=0; j < b.size(); j++) {
if (a[i]==b[j]) {counter++;}
}
This is way to slow for larger vectors. I have thought of an alternating algorithm, but I'm to unskilled to implement it right, so here it is, what I've got yet and my problem:
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (b[j] >= a[i]) {
counter++;
for (int k = i + 1; k < n; k++) {
if (a[k] >= b[j+1]) {
counter++;
for (int l = k + 1; l < m; l++) {
if (b[l] >= a[k]) {
counter++;
....
}
}
}
}
}
}
}
The flow is that I start comparing the first element of a
with the elements of b
. When I have a hit, i jump to vector b
and compare its next element with the elements of a
that come after the element of a
I was comparing with before. (Since the elements of a
and b
are stored in ascending order, once the element of b
I'm comparing with is bigger than the element of a
I change vector on >= not ==)
This should be easy to do with a function that is calling itself, I think. But I can't wrap my head around it.
I hope somebody can even understand what I'm trying to do, but I can't explain it better at the moment. In theory, I think this should be way faster for vectors in ascending order, since you only have to do N comparisons (N being the size of the larger vector) instead of N*M
.