【发布时间】: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++ 是否有类似 std::pair 的东西但只有 3 个元素?
例如:
#include <triple.h>
triple<int, int, int> array[10];
array[1].first = 1;
array[1].second = 2;
array[1].third = 3;
【问题讨论】:
您可能正在寻找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<3> 可能会更好。
类模板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;
【讨论】:
不,没有。
但是,您可以使用tuple 或“双对” (pair<pair<T1,T2>,T3>)。或者 - 显然 - 自己编写课程(这应该不难)。
【讨论】:
只有两种简单的方法可以做到这一点。 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;
【讨论】:
std::tuple。