【问题标题】:Iterable union of two vectors两个向量的可迭代联合
【发布时间】:2013-04-20 20:50:29
【问题描述】:

我有两个数组,如下:

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

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

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;

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

【问题讨论】:

  • 我愿意试一试,@yhager,但你建议如何使用它?
  • 我的回答对你有用吗?如果没有,请帮助我改进它。

标签: c++ boost stl iterator boost-iterators


【解决方案1】:

使用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.

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

【讨论】:

    猜你喜欢
    • 2018-12-19
    • 2012-11-17
    • 2021-12-20
    • 1970-01-01
    • 2017-08-29
    • 2012-10-04
    • 2020-08-08
    • 1970-01-01
    • 2022-08-17
    相关资源
    最近更新 更多