gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:55:42 25 4
gpt4 key购买 nike

我有两个数组,如下:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com