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

47,599

Solution 1

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;

Solution 2

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;

Solution 3

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).

Share:
47,599

Related videos on Youtube

user3432317
Author by

user3432317

Updated on May 21, 2020

Comments

  • user3432317
    user3432317 almost 4 years

    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;
    
    • Raedwald
      Raedwald over 4 years
      This duplicate is worth keeping; it should not be deleted.
  • Drew Delano
    Drew Delano almost 10 years
    C++11 has std::tuple.
  • Sven
    Sven over 3 years
    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>.