I invite you to review @DeadMG's answer.
Rewriting following (most of) his advice, you'd get something like:
#include <cassert>
#include <algorithm>
#include <vector>
std::vector<T> intersection(std::vector<T> const& left_vector, std::vector<T> const& right_vector) {
auto left = left_vector.begin();
auto left_end = left_vector.end();
auto right = right_vector.begin();
auto right_end = right_vector.end();
assert(std::is_sorted(left, left_end));
assert(std::is_sorted(right, right_end));
std::vector<T> result;
while (left != left_end && right != right_end) {
if (*left == *right) {
result.push_back(*left);
++left;
++right;
continue;
}
if (*left < *right) {
++left;
continue;
}
assert(*left > *right);
++right;
}
return result;
}
I've always found taking pairs of iterators awkward, so I would not recommend such an interface. Instead, you could take simply take any "iterable", they need not even have the same value type, so long as they are comparable:
template <typename Left, typename Right>
std::vector<typename Left::value_type> intersection(Left const& left_c, Right const& right_c);
Also, note that I've included some assert
to validate the pre-conditions of the methods (the collections must be sorted) as well as internal invariants (if *left
is neither equal nor strictly less than *right
then it must be strictly greater).
I encourage you to use assert
liberally:
- They document intentions: pre-conditions, invariants, etc...
- They check that those intentions hold.
Documentation & Bug detection rolled in one, with no run-time (Release) cost.
std::set_intersection()
? Reference and example implementations: en.cppreference.com/w/cpp/algorithm/set_intersection \$\endgroup\$