加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 迭代包含在两个范围的交集中的对象

发布时间:2020-12-16 10:05:56 所属栏目:百科 来源:网络整理
导读:标准库中是否有某些东西允许我迭代包含在两个范围的交集中的对象? 特别是,给定一个函数对象动作,我想获得一个相当于的程序 /* some container supporting a push_back operation */ intersection;std::set_intersection(first1,last1,first2,last2,std::bac
标准库中是否有某些东西允许我迭代包含在两个范围的交集中的对象?

特别是,给定一个函数对象动作,我想获得一个相当于的程序

/* 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);

无需插入交叉点.当然,例如,编写这样的代码很容易

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;
        }
    }
}

但我希望标准库中已有可用的东西.

解决方法

您可以使用来自boost的 Function Output Iterator:

#include <boost/function_output_iterator.hpp>
#include <vector>
#include <iostream>
#include <algorithm>

int main() {
    std::vector<int> v1 = {1,2,3,4,5};
    std::vector<int> v2 = {2,4};
    std::set_intersection(v1.begin(),v1.end(),v2.begin(),v2.end(),boost::make_function_output_iterator([](int i) {
                std::cout << i * i << 'n';
            }));
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读