我在搞乱“数组结构”的包装类,最终找到了“boost-iterators”的 zip-iterator。现在我想知道是否有一种方法可以通过迭代生成结果元组,使用结构化绑定,如下面的注释代码段。我发现这篇文章boost::combine,基于范围的 for 和结构化绑定,但这并没有帮助我解决它。
#include <iostream>
#include <numeric>
#include <vector>
#include <boost/iterator/zip_iterator.hpp>
using namespace std;
template <typename T>
struct Buffer2 final
{
vector<T> xs, ys;
auto begin() noexcept
{
return boost::make_zip_iterator(boost::make_tuple(xs.begin(), ys.begin()));
}
auto cbegin() noexcept
{
return boost::make_zip_iterator(boost::make_tuple(xs.cbegin(), ys.cbegin()));
}
auto end() noexcept
{
return boost::make_zip_iterator(boost::make_tuple(xs.end(), ys.end()));
}
auto cend() noexcept
{
return boost::make_zip_iterator(boost::make_tuple(xs.cend(), ys.cend()));
}
};
int main()
{
Buffer2<float> values;
values.xs.resize(10);
values.ys.resize(10);
iota(values.xs.begin(), values.xs.end(), 0);
iota(values.ys.begin(), values.ys.end(), 10);
for (auto value : values)
{
cout << value.get<0>() << ' ' << value.get<1>() << '\n';
}
// This does not work ( x is head_type, y is tail_type )
/* for(auto [x, y] : values) {
cout << x << ' ' << y << '\n';
}*/
}