28

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

For example:

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

array[1].first = 1;
array[1].second = 2;
array[1].third = 3;
Josh Kelley
  • 56,064
  • 19
  • 146
  • 246
user3432317
  • 309
  • 1
  • 3
  • 3

4 Answers4

52

You might be looking for 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;
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • 3
    I believe `std::tuple` has a huge drawback! It cannot be accessed by index. If all types are the same, one would probably be better off with `std::array<3>`. – Sven Aug 28 '20 at 20:04
13

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

#include <tuple>

You can read about this here:

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;
4pie0
  • 29,204
  • 9
  • 82
  • 118
2

No, there isn't.

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

Paweł Stawarz
  • 3,952
  • 2
  • 17
  • 26
-5

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.html like this

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;                           
treshaque
  • 1
  • 1