C++向量元组,按索引从元素创建元组

8
我有一个模板类,其中包含由向量填充的元组。
template<typename ...Ts>
class MyClass
{
    public:
        std::tuple<std::vector<Ts>...> vectors;
};

我希望能够获得新元组,其中包含特定索引处的向量元素。

template<typename ...Ts>
class MyClass
{
public:
    std::tuple<std::vector<Ts>...> vectors;

    std::tuple<Ts...> elements(int index)
    {
        // How can I do this?
    }
};

这真的可行吗?


1
你确定不想要一个元组的向量吗? - LogicStuff
1
@LogicStuff 可能是出于性能原因,请参考 https://en.wikipedia.org/wiki/AOS_and_SOA。 - llllllllll
1个回答

8
在C++14中,您可以通过使用带有索引序列作为附加参数的辅助函数通常技巧来轻松完成它。
template<std::size_t... I> 
auto elements_impl(int index, std::index_sequence<I...>)
{
    return std::make_tuple(
      std::get<I>(vectors).at(index)...
    );
}


auto elements(int index)
{
    return elements_impl(index, std::index_sequence_for<Ts...>{});
}

它只是针对每种类型的序数调用std::get<I>,然后在该位置调用向量的at。我使用at以防万一向量并没有在该索引处持有项目,但如果您的情况不需要检查,则可以替换为operator[]。然后将所有结果发送到make_tuple以构造结果元组对象。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接