+ 1
Can we return two values from a single function?
Can we return two different values from a single function? Is that even possible...
4 Answers
+ 4
You can use std::pair, it can carry two different types which you can define in function template. Here's an example for you : )
#include <iostream>
#include <utility> // std::pair
// References:
// https://en.cppreference.com/w/cpp/utility/pair
// http://www.cplusplus.com/reference/utility/pair/
template <class A, class B>
std::pair<A, B> my_function(A a, B b)
{
std::pair<A, B> rv {a, b};
return rv;
}
int main()
{
std::pair<int, double> sample {my_function(2018, 20.18)};
std::cout << "First (int): "
<< sample.first;
std::cout << "\nSecond (double): "
<< sample.second;
return 0;
}
Hth, cmiiw
+ 4
LOGIC UNIT It seems you had accidentally created two copies of this post, kindly remove the duplicate please
(Edit)
Well, now both threads has answers, but it means you had made duplicates.
https://www.sololearn.com/Discuss/1649728/?ref=app
+ 3
Yes, you can return them in a tuple and acces the first value like this:
print(function()[0])
And the second value like this:
print(function()[1])
The return statement should look like this:
return (value1, value2)
You can have more values in the array and it would still work
+ 3
Wait i just realised that you were asking about c++ so the code doesn't work but the theory still applies