Search code examples
c++tuplesstd-pairstdtuple

Printing Pairs inside tuple in C++


I am trying to print all the values of pair inside of a tuple,

header file

template <typename... Args>
void printPairs(std::tuple<Args...> t)
{
    for (int i = 0; i <= 4; i++)  //the value of 'i' is not usable in a constant expression
    {
        auto pair = std::get<i>(t);
        cout << pair.first << " " << pair.second << endl;
    }
}

Main.cpp

std::tuple<std::pair<int, int>, std::pair<int, int>, std::pair<int, int>, std::pair<int, int>> t1 = {std::make_pair(1, 2), std::make_pair(3, 4), std::make_pair(5, 6), std::make_pair(7, 8)};
printPairs(t1);

If you would not iterate and put a constant value instead of "i", works fine

auto pair = std::get<1>(t);
 cout << pair.first << " " << pair.second << endl;

Solution

  • You can use std::apply:

    template<typename Tuple>
    void printPairs(const Tuple& t) {
      std::apply([](const auto&... pair) {
        ((std::cout << pair.first << " " << pair.second << std::endl), ...);
      }, t);
    }