如何在 C++ 中创建元组向量?

How to create a vector of tuples in C++?

有一个生成器,每次迭代生成一个包含 16 个整数的元组。我想将这些元组添加到一个向量中。创建向量时,我必须写 std::vector<std::tuple<int, int, .... 16 times>>。是否有另一种方法来创建这些元组的向量。

测试包含 5 个整数的元组情况的代码:

#include "cppitertools/itertools.hpp"
#include <iostream> 
#include <tuple>
#include <vector> 

int main()
{
    std::vector<int> v1{0, 1};
    std::vector<std::tuple<int, int, int, int, int>> states;

    for (auto&& i : iter::product<5>(v1)) 
    {
        states.push_back(i);
    }

    auto size = states.size();
    std::cout << size << std::endl;

}

我正在使用 cppiterator

template<size_t Remaining, typename Type,typename ... Args>
struct make_tuple_n_impl{
    using type=typename make_tuple_n_impl<Remaining-1,Type,Type,Args...>::type;
};

template<typename T,typename ... Args>
struct make_tuple_n_impl<0,T,Args...>{
    using type=std::tuple<Args...>;
};

template<size_t Count,typename Type>
using tuple_of=typename make_tuple_n_impl<Count,Type>::type;

那么tuple_of<5,int>就是std::tuple<int,int,int,int,int>.

您可以 fiddle iter::product 创建的元组类型

#include "cppitertools/itertools.hpp"
#include <iostream> 
#include <tuple>
#include <vector> 

template <typename>
struct remove_tuple_reference;

template <typename... Ts>
struct remove_tuple_reference<std::tuple<Ts...>> {
    using type = std::tuple<std::remove_reference_t<Ts>...>;
};

template <typename T>
using remove_tuple_reference_t = typename remove_tuple_reference<T>::type;

int main()
{
    std::vector<int> v1{0, 1};
    using tup = remove_tuple_reference_t<decltype(iter::product<5>(v1).begin())::value_type>;
    std::vector<tup> states;

    for (auto&& i : iter::product<5>(v1)) 
    {
        states.push_back(i);
    }

    auto size = states.size();
    std::cout << size << std::endl;

}