There can be some instances where you need to return multiple values (may be of different data types ) while solving a problem. One method to do the same is by using pointers, structures or global variables, already discussed here
There is another interesting method to do the same without using the above methods, using tuples (for returning multiple values ) and pair (for two values).
We can declare the function with return type as pair or tuple (whichever required) and can pack the values to be returned and return the packed set of values. The returned values can be unpacked in the calling function.
- A tuple is an object capable to hold a collection of elements where each element can be of a different type.
- Class template
std::tupleis a fixed-size collection of heterogeneous values
- This class couples together a pair of values, which may be of different types
- A pair is a specific case of a std::tuple with two elements
Note : Tuple can also be used to return two values instead of using pair .
Values returned by tuple: 10 5 a Values returned by Pair: 2 5
This article is contributed by Mayank Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Declare a C/C++ function returning pointer to array of integer pointers
- Passing and Returning Objects in C++
- How can I return multiple values from a function?
- How to return multiple values from a function in C or C++?
- Efficient ways to compare a variable with multiple values
- All possible values of floor(N/K) for all values of K
- Sorting of Vector of Tuple in C++ (Ascending Order)
- Sorting of Vector of Tuple in C++ (Descending Order)
- How to iterate over the elements of an std::tuple in C++
- Lex program to take input from file and remove multiple spaces, lines and tabs
- Creating multiple process using fork()
- C function argument and return values
- Difference between Single and Multiple Inheritance in C++
- Sorting an array according to another array using pair in STL
- How to delete a range of values from the Set using Iterator
- How to delete a range of values from the List using Iterator
- Queries for elements having values within the range A to B in the given index range using Segment Tree
- How Linkers Resolve Global Symbols Defined at Multiple Places?
- Multiple Inheritance in C++
- Socket Programming in C/C++: Handling multiple clients on server without multi threading