Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are Tuples in C++?
2.1.
Declaration 
2.2.
Initialization
3.
Functions available for Tuples in C++
3.1.
Size of the Tuple 
3.2.
Accessing the elements of the Tuple
3.3.
Updating the elements of the Tuple
3.4.
Swapping the elements of two Tuples 
3.5.
Unpacking the Tuple
3.6.
Concatenating the Tuples
4.
Applications of Tuples
5.
FAQs
6.
Key Takeaways 
Last Updated: Mar 27, 2024
Easy

Tuples in C++

Author Vidhi Singh
0 upvote

Introduction

Whenever we intend to store several elements together while coding in C++, we generally think of using an array, and when we are not sure of the exact number of elements, we employ vectors. But, while using arrays or vectors, we ensure that all elements have the same data type.

Let’s say we have a set of elements that need to be stored together under a single name but have different data types. C++ has a Standard Template Library of Tuple to deal with this type of problem. 

Also see, Literals in C.Fibonacci Series in C++

What are Tuples in C++?

In C++, a tuple is a built-in class that is a collection of elements that can be of different data types. Although tuples can have any arbitrary length, but once declared, they are of fixed length. In other words, whatever length has been given to the Tuple remains fixed throughout as they are immutable. 

They are somehow similar to the Pair STL in C++. It is just that they are a generalized form of Pairs as a Pair can only store two elements while Tuples can store any number of elements. Although both of these have the ability to store heterogeneous elements, the difference stands in the number of elements that can be stored.

Declaration 

In C++, they come in the <tuple> class which needs to be included as header.

#include<tuple>
You can also try this code with Online C++ Compiler
Run Code

 

For declaring a tuple, the ‘tuple’ keyword is used, followed by the different data types that it will store. The order in which the data types are specified here is the order in which they will be stored and accessed. 

For example, a tuple that stores elements with data type boolean, character and string respectively will be declared as follows: 

tuple<bool,char,string> example;
You can also try this code with Online C++ Compiler
Run Code

Initialization

Initialization of a tuple in C++ can be done while declaring it and after declaring it as well. 

Initializing while declaring

This includes providing the values to the Tuple while declaring it. This is done by writing the values in brackets() just after declaring as follows:

tuple<bool,char,string> example(true,'C',"CodingNinjas");  
You can also try this code with Online C++ Compiler
Run Code

 

Initializing after declaring

This includes providing the values to the Tuple after it has been declared in a new line of code. This is done using the function make_tuple(). Inside the brackets, the values are passed as arguments in the same order as they are specified at the time of declaration as follows:

tuple<bool, char, string> example;
example = make_tuple(true, 'C', "CodingNinjas");
You can also try this code with Online C++ Compiler
Run Code

Also Read - C++ Interview Questions

Functions available for Tuples in C++

Size of the Tuple 

Tuple_size: This function is used to get the number of elements in the tuple. 

For example:

#include <iostream>
#include <tuple>
using namespace std;
int main()
{
	tuple<bool, char, string> example(true, 'C', "CodingNinjas");
	cout << tuple_size < decltype(example) >::value;	//prints the number of elements
	return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

3

 

In C++, “decltype” is basically an operator that inspects the type of expression passed to it.

Accessing the elements of the Tuple

To access any element from the Tuple, get() function is used. It takes the index and the tuple name as the argument. The elements cannot be directly retrieved using [] similar in the case of arrays and vectors as there might be elements with different data types and therefore occupy different space in memory as well.

For example: 

#include<iostream>
#include <tuple>
using namespace std;
int main()
{
	tuple<bool, char, string> example(true, 'C', "CodingNinjas");
	cout <<get<2> (example);	//prints the 0th element
	return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

CodingNinjas

 

Unlike arrays and vectors, there is no built-in function to iterate over all the elements of a tuple.

Updating the elements of the Tuple

To update the already existing or non-existing value of a tuple, get() function is used.
 

For Example:

#include <iostream>
#include <tuple>
using namespace std;
int main()
{
	tuple<bool, char, string> example;
	get<2> (example) = "CodingNinjas";	// assigning value to 2nd index in the tuple 
	cout <<get<2> (example);
	return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output: 

CodingNinjas

Swapping the elements of two Tuples 

The elements of two tuples can be swapped using swap() function. One of the tuples is passed as an argument. 

The constraint here is that both the tuples must-have elements of the same data type in the same order. In case it is not so, it produces an error.

For example:  

#include <iostream>
#include <tuple>
using namespace std;
int main()
{
	tuple<bool, char, string> example1(true, 'C', "Coding");
	tuple<bool, char, string> example2(false, 'N', "Ninjas");
	cout << "Before swap example1 element 1" << " ";
	cout <<get<1> (example1) << ”\n”;
	example1.swap(example2);	//swapping the elements of example1 with example2 
	cout << "After swap example1 element 1" << " ";
	cout <<get<1> (example1) << ”\n”;
	return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

Before swap example1 element 1 C
After swap example1 element 1 N

 

Try and compile with online c++ compiler.

Unpacking the Tuple

In C++, unpacking the Tuple means storing the elements of the Tuple into different individual variables. This is achieved through tie() function. 

For example: 

#include <iostream>
#include <tuple>
using namespace std;
int main()
{
	bool flag;
	char c;
	string s;
	tuple<bool, char, string> example(true, 'C', "Coding");
	tie(flag, c, s) = example;	//unpacking the elements of tuple 
	cout << flag << " " << c << " " << s;
	return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

1 C Coding

 

In case there is only a requirement of few elements only, the ‘ignore’ keyword is used.

For example:

#include <iostream>
#include <tuple>
using namespace std;
int main()
{
	bool flag;
	string s;
	tuple<bool, char, string> example(true, 'C', "Coding");
	tie(flag, ignore, s) = example;	//unpacking the elements using ignore
	cout << flag << " " << s;
	return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

1 Coding

Concatenating the Tuples

Concatenation of two or more tuples is also possible in C++. This can be done using tuple_cat() function. This function takes the name of all the tuples as arguments. It produces a tuple that has all the elements of the concatenated tuples in order one after another. 

To store the produced Tuple, either a new tuple can be declared, or the use of auto keyword to define the data type can be done.

For example:

#include <iostream>
#include <tuple>
using namespace std;
int main()
{

	tuple<bool, char, string> example1(true, 'C', "Coding");
	tuple<bool, char, string> example2(false, 'N', "Ninjas");
	tuple<bool, char, string> example3(true, 'C', "CN");
	auto all = tuple_cat(example1, example2, example3);	//concatenating the tuples 
	return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Applications of Tuples

Since tuples can store elements with heterogeneous data types, they take away the headache of declaring a lot of variables, especially when they are related to each other. So, tuples come with mostly all the functionalities as arrays and vectors, plus allowing to store elements of different data types. 

Well, you may argue that whatever a tuple can do, a structure or class can also achieve in C++. Yes, of course. For that let’s consider the following application.
Tuples seem to be typical of use when more than one value needs to be returned by a function, and all these values have different data types. 

For example: 

tuple<int, bool> return_values()
{
	return make_tuple(1, true);
}
You can also try this code with Online C++ Compiler
Run Code

 

In these cases, tuples make it convenient as if the structure would have been used; a separate declaration would have to be made at the start. Therefore, using a tuple in such scenarios saves the programmer from the hassle of defining a dedicated structure only for a specific purpose. 

Declaring a structure in cases like these is not a wise idea. Tuples also tend to make the code more compact.

Check out this article - C++ String Concatenation

FAQs

  1. Are tuples available in all versions on C++?
    No, C++ Standard Library for Tuples is included in C++ 14 and C++ 17 only.
     
  2. Can tuples be used in place of struct?
    They are similar when it comes to storing data of heterogeneous data type together. But both have their applications in different scenarios as struct needs to be defined whereas a tuple can be used directly using the make_tuple() function. So, whenever, the same heterogeneous data types need to be stored together many times, struct should be employed. 
     
  3. Can tuples be used in place of classes?
    No, tuples don’t have their member functions.

Key Takeaways 

This article explains the tuples in C++ by exploring in detail the in-built functions it supports, operations that can be performed on tuples, and operations that cannot be performed on them. It also throws light on specific cases when Tuples are useful in C++.  
We hope that this blog has helped you enhance your knowledge regarding Tuples in C++ and if you would like to learn more, check out our articles on C++. Do upvote our blog to help other ninjas grow. 
Happy Coding!

Live masterclass