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
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above