我有兩個沒有重複的已排序C++ std ::向量(您可以稱它們爲集合),我想知道它們是否相交。我不需要共同元素的向量。如何使用C++ STL和boost來判斷兩個已排序的向量是否相交
我在boost問題的範圍內使用boost :: set_intersection算法編寫了這個問題最後的代碼(http://www.boost.org/doc/libs/1_50_0/libs/range/doc /html/range/reference/algorithms/set.html)。這段代碼避免了構造一組通用元素,但是掃描了矢量的所有元素。
是否有可能改善我的功能「相交」使用boost和C++ STL而不使用循環?我想停止向量中的第一個通用元素,或者至少避開我的counter類。
增強範圍庫提供「包含」和「set_intersection」,但不是「相交」。這使我認爲「相交」是微不足道的或在其他地方提供,但我找不到它。
謝謝!
#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;
}
你爲什麼要用'boost'?有'std :: unique'和'std :: set_intersection'。 –
我不認爲你可以改善你的功能,而無需編寫自己的循環。 – jrok