I have two sorted C++ std::vector without duplicates (you could call them sets) and I want to know if they intersect. I do not need the vector of common elements.
I wrote the code at the end of this question using the boost::set_intersection algorithm in the boost "range" library (http://www.boost.org/doc/libs/1_50_0/libs/range/doc/html/range/reference/algorithms/set.html). This code avoids constructing the set of common elements but does scan all the elements of the vectors.
Is it possible to improve my function "intersects" using boost and the C++ STL without using a loop? I'd like to stop at the first common element in the vectors or at the very least avoid my counter class.
The boost range library provides "includes" and "set_intersection" but not "intersects". This makes me think that "intersects" is trivial or provided elsewhere but I cannot find it.
thanks!
#include <vector>
#include <string>
#include <boost/assign/list_of.hpp>
#include <boost/function_output_iterator.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/range/algorithm_ext/erase.hpp>
template<typename T>
class counter
{
size_t * _n;
public:
counter(size_t * b) : _n(b) {}
void operator()(const T & x) const
{
++*_n;
}
};
bool intersects(const std::vector<std::string> & a, const std::vector<std::string> & b)
{
size_t found = 0;
boost::set_intersection(a, b, boost::make_function_output_iterator(counter<std::string>(&found)));
return found;
}
int main(int argc, char ** argv)
{
namespace ba = boost::assign;
using namespace std;
vector<string> a = ba::list_of(string("b"))(string("vv"))(string("h"));
vector<string> b = ba::list_of(string("z"))(string("h"))(string("aa"));
boost::erase(a, boost::unique<boost::return_found_end>(boost::sort(a)));
boost::erase(b, boost::unique<boost::return_found_end>(boost::sort(b)));
cout << "does " << (intersects(a, b) ? "" : "not ") << "intersect\n";
return 0;
}