c++ - 两个 vector 的可迭代并集

标签 c++ boost stl iterator boost-iterators

我有两个数组,如下:

std::array<int,6> A,B;
//Fill A with random data
//File B with random data

无论出于何种原因,我想要某种容器对象,它可以让我单独访问两个 vector ,还可以迭代它们的并集,从而允许执行如下操作:

union_container uc(A,B);
for(unioned::iterator i=uc.begin();i!=uc.end();++i)
  *i+=1;
uc.first()[2]=4;
uc.second()[4]=5;

我可以自己编写这个 union 类,但也许已经有一个库允许这样做?

最佳答案

使用 Boost zip iterators 是一种方法。

#include <array>
#include <functional>
#include <iostream>
#include <boost/tuple/tuple.hpp>
#include <boost/iterator/zip_iterator.hpp>

template<typename T>
using ZipIt = boost::zip_iterator< boost::tuple<T*, T*> >;

template<typename T>
using ZipRef = decltype(*ZipIt<T>());

template<typename T>
void operator+=(ZipRef<T> z, T const& v)
{
    z.template get<0>() += v;
    z.template get<1>() += v;    
}

int main()
{
    std::array<int, 6> a = { 1, 3, 5, 7,  9, 11 };
    std::array<int, 6> b = { 2, 4, 6, 8, 10, 12 };

    std::for_each(
        boost::make_zip_iterator(boost::make_tuple(std::begin(a), std::begin(b))), 
        boost::make_zip_iterator(boost::make_tuple(std::end(a), std::end(b))), 
        [](ZipRef<int> z){ z += 1; }
    );

    std::copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, ",")); std::cout << "\n";
    std::copy(std::begin(b), std::end(b), std::ostream_iterator<int>(std::cout, ",")); std::cout << "\n";

    a[2] = 4;
    b[4] = 5;
}

在线 output .

请注意,上面的代码并不像我希望的那样通用,因为跳转到可变参数模板和通用迭代器类型证明有点毛茸茸(留作练习!)这主要与以下事实有关 boost::zip_iteratorboost::tuple 周围使用了一些棘手的内部外观。出于这个原因,我还在 ZipRef 的模板别名中使用了 decltype 以避免必须在 std::for_each lambda 表达式中编写此类讨厌的类型.

关于c++ - 两个 vector 的可迭代并集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16240514/

相关文章:

c++ - 静态成员有不同的值

c++ - Directx11加载纹理

c++ - 了解以下 cpp 片段

c++ - 如何在 boost::gregorian::date 中转换 days_ 中的值

c++ - 释放由 std::make_tuple() 创建的元组

c++ - 将指向类成员函数的指针作为参数传递

c++ - Vim 搜索类

multithreading - 使用多线程和互斥锁时对互斥锁的断言

c++ - 对 C++ 类进行 STL 化

c++ - 我需要一些 C++ 专家关于扩展 std::string 的意见