c++ - 如何创建一个 std::tuple,其中包含来自索引元组指定的 vector 中的成员?

标签 c++ stl variadic-templates

我有一些值的 std::vector,例如 std::vector<std::string> v = {"a", "b", "c", "d", "e"};然后我有一个从参数包创建的数字元组(即它可以有任何大小)。如何创建 vector 成员的元组(这里是 std::string 的元组),它使用索引元组作为 vector 的索引?例如,如果索引元组的值为 0、3、1,那么结果应该与我写的相同 auto result = std::make_tuple("a", "d", "b"); .我正在使用 Visual Studio 2015。

编辑:澄清索引元组

最佳答案

也许是这样的:

template <typename C, typename Tuple, int... Is>
auto project_impl(const C& c, const Tuple& indices, 
                  std::integer_sequence<int, Is...>) {
  return std::make_tuple(c[std::get<Is>(indices)]...);
}

template <typename C, typename Tuple>
auto project(const C& c, const Tuple& indices) {
  return project_impl(c, indices,
    std::make_integer_sequence<int, std::tuple_size<Tuple>::value>());
}

Demo

关于c++ - 如何创建一个 std::tuple,其中包含来自索引元组指定的 vector 中的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42138790/

相关文章:

c++ - 可变参数模板包扩展

c++ - 有没有办法使用相同的索引遍历std::tuple和std::array?

c++ - 通过两个隐式构造函数构造一个值?

c++ - 编译器错误{匿名}

c++ - 菊花链可变参数模板类

c++ - STL 容器在该类的声明中持有类

c++ - C++ 中线段树的 STL

c++ - 将 DLL 链接到 Visual C++ 时未定义的外部

c++ - 调整嵌套 std::vector 的大小

c++ - 在 C++ 中从给定的未排序整数 vector 中获取最长排序元素序列的最简单方法