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

C++Server Side ProgrammingProgramming

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<iostream>
#include<tuple>
#include<utility>
using namespace std;
tuple<int, string, char> my_function_tuple(int x, string y) {
   return make_tuple(x, y, 'A'); // make tuples with the values and return
}
std::pair<int, string> 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<int, string> my_pair = my_function_pair(89,"World"); //get pair from function
   cout << "Values in tuple: ";
   cout << "(" << a << ", " << b << ", " << c << ")" << endl;
   cout << "Values in Pair: ";
   cout << "(" << my_pair.first << ", " << my_pair.second << ")" << endl;
}

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<iostream>
using namespace std;
int my_func(int N) { //function with integer type parameter
   cout << "Calling function my_func(int)";
}
int my_func(char* str) { //overloaded function with char* type parameter
   cout << "calling function my_func(char *)";
}
int main() {
   my_func(nullptr); //it will call my_func(char *), but will generate compiler error
}

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.

raja
Published on 08-May-2019 09:16:43
Advertisements