重複のない 2 つの並べ替えられた C++ std::vector (セットと呼ぶことができます) があり、それらが交差するかどうかを知りたいです。共通要素のベクトルは必要ありません。
ブースト「範囲」ライブラリ(http://www.boost.org/doc/libs/1_50_0/libs/range/doc/html/range)のboost::set_intersectionアルゴリズムを使用して、この質問の最後にコードを書きました/reference/algorithms/set.html)。このコードは、共通要素のセットの構築を回避しますが、ベクトルのすべての要素をスキャンします。
ループを使用せずにブーストと C++ STL を使用して関数の「交差」を改善することは可能ですか? ベクトルの最初の共通要素で停止するか、少なくともカウンター クラスを避けたいと思います。
ブースト範囲ライブラリは、「includes」と「set_intersection」を提供しますが、「intersects」は提供しません。これにより、「交差」は些細なことであるか、他の場所で提供されていると思いますが、見つかりません。
ありがとう!
#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;
}