標準庫中是否存在允許我遍歷包含在兩個範圍的交集中的對象的內容?迭代包含在兩個範圍的交集中的對象
特別地,給定的一個功能對象action
,我想獲得一個程序,它是等效於
/* some container supporting a push_back operation */ intersection;
std::set_intersection(first1, last1, first2, last2,
std::back_inserter(intersection));
for (auto const& element : intersection)
action(element);
,而不需要插入到intersection
。當然,寫這樣的代碼很容易,例如
template<class InputIt1, class InputIt2, class UnaryFunction>
void for_each_in_intersection(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2, UnaryFunction f)
{
while (first1 != last1 && first2 != last2)
{
if (*first1 < *first2)
++first1;
else
{
if (!(*first2 < *first1))
f(*first1++);
++first2;
}
}
}
但我希望標準庫中已經有一些東西可用。
你只是想指針的容器來遍歷? – wally
Range-v3,Boost.Iterator,Boost.Range等都具有此功能,但它不直接在stdlib中。 – ildjarn
@Muscampester號只需看看[在cppreference.com上可能實現'std :: set_intersection]](http://en.cppreference.com/w/cpp/algorithm/set_intersection)。我想用'* d_first ++ = * first1 ++;'替換爲'action(* first1 ++);'替換相同的代碼。 – 0xbadf00d