I want to solve a problem, which needs the largest sum of the subarray and it's position. The program's solution is in pseudocode from the book Introductions to algorithms, however it contains a returning which contains 3 elements (low,high,sum). What can I do about this? How can I return three elements? The program is easily understandable, however the returning makes me unable to transform it to c++.
Asked
Active
Viewed 344 times
-1

Dani Suba
- 27
- 6
-
2You can either create a struct/class, use a vector/array or pass variables by reference. – Devolus Mar 09 '21 at 14:59
1 Answers
3
You could write a struct containing 3 int
s and return that from the function:
struct data
{
int low, mid, high;
};
data fun( /* args ... */ )
{
// ...
return {low, mid, high};
}
Alternatively, if you don't want to name the structure explicitly, you could just return a std::tuple
containing 3 int
s.
std::tuple<int, int, int> fun( /* args ... */ )
{
// ...
return {low, mid, high};
}
In either case, at the call site you can write:
auto [low, mid, high] = fun();

cigien
- 57,834
- 11
- 73
- 112