【问题标题】:Does C++ provide a "triple" template, comparable to pair<T1, T2>? [duplicate]C++ 是否提供与 pair<T1, T2> 相当的“三重”模板? [复制]
【发布时间】:2014-07-01 12:16:49
【问题描述】:

C++ 是否有类似 std::pair 的东西但只有 3 个元素?

例如:

#include <triple.h>
triple<int, int, int> array[10];

array[1].first = 1;
array[1].second = 2;
array[1].third = 3;

【问题讨论】:

  • 这个副本值得保留;它不应该被删除。

标签: c++ stl std-pair


【解决方案1】:

您可能正在寻找std::tuple:

#include <tuple>

....

std::tuple<int, int, int> tpl;

std::get<0>(tpl) = 1;
std::get<1>(tpl) = 2;
std::get<2>(tpl) = 3;

【讨论】:

  • 我相信std::tuple有一个巨大的缺点!它不能通过索引访问。如果所有类型都相同,那么使用std::array&lt;3&gt; 可能会更好。
【解决方案2】:

类模板std::tuple 是一个固定大小的异构值集合,自 C++11 起在标准库中可用。它是std::pair 的概括,并在标题中显示

#include <tuple>

你可以在这里阅读:

http://en.cppreference.com/w/cpp/utility/tuple

例子:

#include <tuple>

std::tuple<int, int, int> three;

std::get<0>( three) = 0;
std::get<1>( three) = 1;
std::get<2>( three) = 2;

【讨论】:

    【解决方案3】:

    不,没有。

    但是,您可以使用tuple 或“双对” (pair&lt;pair&lt;T1,T2&gt;,T3&gt;)。或者 - 显然 - 自己编写课程(这应该不难)。

    【讨论】:

      【解决方案4】:

      只有两种简单的方法可以做到这一点。 1)自己实施。 2) 得到提升并像这样使用 boost::tuple http://www.boost.org/doc/libs/1_55_0/libs/tuple/doc/tuple_users_guide.html

      double d = 2.7; A a;
      tuple<int, double&, const A&> t(1, d, a);
      const tuple<int, double&, const A&> ct = t;
        ...
      int i = get<0>(t); i = t.get<0>();       
      int j = get<0>(ct);                      
      get<0>(t) = 5;                           
      

      【讨论】:

      • C++11 有std::tuple
      猜你喜欢
      • 1970-01-01
      • 2011-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-13
      相关资源
      最近更新 更多