How to iterate over the elements of an std::tuple in C++
Last Updated :
20 May, 2021
A C++ tuple is a container that can store multiple values of multiple types in it. We can access the elements of the tuple using std::get(), but std::get() always takes a constant variable parameter, so we can not simply iterate through it using a loop. For tasks that require iterating through all elements of the tuple. like printing all elements.
Below is the program to illustrate the iterating over an element tuple:
CPP14
#include <iostream>
#include <string>
#include <tuple>
int main()
{
std::tuple<std::string, std::string,
std::string>
tup( "Geeks" , "for" , "Geeks" );
std::cout << "Values of tuple: " ;
std::cout << std::get<0>(tup)
<< " " << std::get<1>(tup)
<< " " << std::get<2>(tup)
<< std::endl;
tup = std::make_tuple( "Hey" , "Welcome to" ,
"Geeksforgeeks" );
std::cout << "Values of tuple(Modified): " ;
std::cout << std::get<0>(tup) << " "
<< std::get<1>(tup) << " "
<< std::get<2>(tup)
<< std::endl;
return 0;
}
|
Output:
Values of tuple: Geeks for Geeks
Values of tuple(Modified): Hey Welcome to Geeksforgeeks
The problem arises when we try to iterate through the whole tuple. So, we have two methods here, to iterate through the values of a tuple:
- Using Variadic Templates and metaprogramming (No use of std::apply).
- Using Variadic Templates and std::apply.
Using Variadic Templates and Template:
Variadic templates are used to pass multiple arguments packed in one template argument, and that can be expanded later inside the function. Here is how we will go through all elements of a tuple.
Below is the implementation of the same:
CPP
#include <iostream>
#include <string>
#include <tuple>
using namespace std;
template < size_t I = 0, typename ... Ts>
typename enable_if<I == sizeof ...(Ts),
void >::type
printTuple(tuple<Ts...> tup)
{
return ;
}
template < size_t I = 0, typename ... Ts>
typename enable_if<(I < sizeof ...(Ts)),
void >::type
printTuple(tuple<Ts...> tup)
{
cout << get<I>(tup) << " " ;
printTuple<I + 1>(tup);
}
int main()
{
tuple<string, string, string> tup( "Geeks" ,
"for" ,
"Geeks" );
printTuple(tup);
return 0;
}
|
This case is very much simplified using constexpr() function and if constexpr expressions, but that are only available from C++17 onward. I am simplified code for that too, you can run that in C++17.
Below is the implementation of the above approach:
CPP
#include <iostream>
#include <string>
#include <tuple>
using namespace std;
template < size_t I = 0, typename ... Ts>
contexpr void printTuple(tuple<Ts...> tup)
{
if
constexpr(I == sizeof ...(Ts))
{
return ;
}
else {
cout << get<I>(tup) << " " ;
printTuple<I + 1>(tup);
}
}
int main()
{
tuple<string, string, string> tup( "Geeks" ,
"for" ,
"Geeks" );
printTuple(tup);
return 0;
}
|
Output:
Below is the output of the above code:

Explanation:
The requirement of std::get() is a constant index, no variable. We can always specify a constant number for a template function, “I” here is a constant number for the function. So, we will have n+1 instantiations of print_num() function, where n is the size of the tuple, each one has “I” as a constant number for itself. So instantiations of these functions will be like print_tuple, print_tuple, …., and print_tuple, and all these functions will be called in sequence. This is Template Metaprogramming
Note: So, you can not run the above code on Geeksforgeeks IDE, you need to run it on another compiler. If you want to use C++14 or C++11 you can use the first method. Tuples and templates are only available from C++11, so can not use older versions.
Using Variadic Templates and std::apply():
- First, a simple guide on what std::get() is. std::get() implements some function on elements of tuples, considering elements of tuples as values for that function. It takes one function f(x, y, z….) and a tuple (x, y, z…) which are arguments for the function, and returns the value returned by f.
- Now one more thing, about variadic expansion, if we need to apply some function on all values of a variadic template, then we do it like foo(Ts)…, where Ts is our variadic template, and foo() is the function which needs to be applied on all values packed in Ts. Here three dots after function “…” means the function is applied to the expansion of the variadic template.
- Lambda functions are anonymous functions, which can be easily declared and applied. They are implemented like:
[&a, b, c] (int x, float &y) {
// Function Body
}
- Here x and y are arguments to the function where x is passed by values and y by reference. And, x, y, and z are variables that will be used inside the function for some purpose, so they are fed to function, which means they will be available inside the scope of function.
Below is the implementation of the same:
CPP
#include <iostream>
#include <string>
#include <tuple>
template < typename ... Ts>
void printTuple(std::tuple<Ts...> tup)
{
std:: size_t length = sizeof ...(Ts);
std::apply(
[length]( auto const &... ps) {
std::cout << "[ " ;
int k = 0;
((std::cout << ps
<< (++k == length ? "" : "; " )),
...);
std::cout << " ]" ;
},
tuple);
}
int main()
{
std::tuple<std::string,
std::string, std::string>
tup( "Geeks" , "for" , "geeks" );
printTuple(tup);
return 0;
}
|
- Output:
Below is the output of the above code:

Note: std::apply() is only available from C++17. So, you can not run this code on Geeksforgeeks IDE, you need to run it on another compiler. If you want to use C++14 or C++11 you can use the first method. Tuples and templates are only available from C++11, so can not use older versions.
Similar Reads
How to Iterate Over a Set of Pairs in C++?
In C++, a set is a container that stores unique values in some specified order while pairs are data structures that store key-value pairs. In this article, we will look at how we can iterate through a set of pairs in C++. For Example, Input: mySet = { {100: "Geek"}, {200:" for"}, {300:" Geeks"} } Ou
2 min read
How to Insert Elements into a Set Using Iterator in C++?
In C++, a set is a container provided by the Standard Template Library(STL) that stores unique elements of the same type in a sorted order. In this article, we will learn how to use an iterator to insert elements into a set in C++. Example: Input: myVector = {10, 20, 30, 40, 50} Output: myVector = {
2 min read
How to Iterate Over a Vector of Pairs in C++?
In C++, vectors are dynamic arrays that allow users to store data in a contiguous memory location while pairs are data structures that allow the users to store two heterogeneous values together in the key-value pair. In this article, we are to learn how we can iterate over a vector of pairs in C++.
2 min read
How Do I Iterate Over the Words of a String?
In C++, strings are character sequences stored in a char array. It may contain text in the form of multiple words representing a sentence. In this article, we will learn how we can iterate over the words of a string in C++. Example: Input: myString ="Geek for Geeks" Output: Geek for GeeksIterate Ove
2 min read
How to Access Vector Element Using Iterator in C++?
In C++, vectors are container that works like a dynamic array. STL provides iterators for the traversal of these containers. In this article, we will learn how to access an element in a vector using an iterator in C++. Example Input: myVector = {1, 5, 8, 1, 3, 4} Output: myVector value at index 5 us
2 min read
How to find the sum of elements of a Vector using STL in C++?
In this article, we will find the sum of all the elements of the vector using STL in C++. The simplest method to find the sum of all elements of vector using STL is accumulate() method. Letâs take a look at a simple example: [GFGTABS] C++ #include <bits/stdc++.h> using namespace std; int main(
2 min read
How to Access Elements of Set of Maps in C++?
In C++, a set of maps can be used to store multiple maps of key-value pairs sorted according to their number and values of elements such as graphs. In this article, we will explore how we can access the elements of a set of maps in C++. Example: Input: { { {1: "C++"}, {2:" Python"} }, { {3:" Java"},
2 min read
How to Find the Last Element in a Set in C++?
In this article, we will learn how to find the last element is a set in C++. The most efficient way to find the last element of set is by using set rbegin() function. Letâs take a look at a simple example: [GFGTABS] C++ #include <bits/stdc++.h> using namespace std; int main() { set<int>
2 min read
How to Find the Second Occurrence of an Element in Vector in C++?
In C++, vector containers store the data in a contiguous memory location like arrays and also can resize themselves to store more elements. In this article, we will learn how to find the second occurrence of a specific element in a vector in C++. Example Input: myVector = {20, 30, 10, 50, 10, 80, 10
2 min read
How to Insert Multiple Elements to a Multiset in C++?
In C++, a multiset is a container that stores elements in a specific order. Multiple elements can have the same values. In this article, we will learn how to insert multiple elements into a multiset in C++. Example: Input: myMultiset = {1, 4, 5, 9}; ElementsToBeAdded = {2, 3, 4} Output: myMultiset =
2 min read