Returning multiple values from a function using Tuple and Pair in C++

In C or C++, we cannot return more than one value from a function. To return multiple values, we have to provide output parameter with the function. Here we will see another approach to return multiple value from a function using tuple and pair STL in C++.

The Tuple is an object capable to hold a collection of elements, where each element can be of different types.

The pair can make a set of two values, which may be of different types. The pair is basically a special type of tuple, where only two values are allowed.

Let us see one example, where we will see how to tuple and pairs are working.

Example

#include
#include
#include
using namespace std;
tuple my_function_tuple(int x, string y) {
   return make_tuple(x, y, 'A'); // make tuples with the values and return
}
std::pair my_function_pair(int x, string y) {
   return std::make_pair(x, y); // make pair with the values and return
}
main() {
   int a;
   string b;
   char c;
   tie(a, b, c) = my_function_tuple(48, "Hello"); //unpack tuple
   pair my_pair = my_function_pair(89,"World"); //get pair from function
   cout 

Output

Values in tuple: (48, Hello, A)
Values in Pair: (89, World)

So what is the problem in the above program? The NULL is typically defined as (void*)0. We are allowed to convert NULL to integral type. So the function call of my_func(NULL) is ambiguous.

If we use the nullptr in the place of NULL, we will get the result like below −

Example

#include
using namespace std;
int my_func(int N) { //function with integer type parameter
   cout 

Output

calling function my_func(char *)

We can use the nullptr at all places where NULL is expected. Like the NULL, the nullptr also can be converted into any pointer type. But this is not implicitly convertible to integral type like NULL.

Updated on: 2019-07-30T22:30:26+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements