C++ 是否提供了“三重”模板,可与 pair<T1, T2> 相媲美?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23637765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:30:53  来源:igfitidea点击:

Does C++ provide a "triple" template, comparable to pair<T1, T2>?

c++stlstd-pair

提问by user3432317

Does C++ have anything like std::pairbut with 3 elements?

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

For example:

例如:

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

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

回答by juanchopanza

You might be looking for std::tuple:

您可能正在寻找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;

回答by 4pie0

Class template std::tupleis a fixed-size collection of heterogeneous values, available in standard library since C++11. It is a generalization of std::pairand presented in header

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

#include <tuple>

You can read about this here:

你可以在这里阅读:

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

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

Example:

例子:

#include <tuple>

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

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

回答by Pawe? Stawarz

No, there isn't.

不,没有。

You can however use a tupleor a "double pair" (pair<pair<T1,T2>,T3>). Or - obviously - write the class yourself (which shouldn't be hard).

但是,您可以使用元组或“双对” ( pair<pair<T1,T2>,T3>)。或者 - 显然 - 自己编写课程(这应该不难)。

回答by treshaque

There are only 2 simple way to get that. 1) To implement it yourself. 2) get the boost and use boost::tuple http://www.boost.org/doc/libs/1_55_0/libs/tuple/doc/tuple_users_guide.htmllike this

只有两种简单的方法可以做到这一点。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;