I am trying to implement a bottom up approach function to the rod cutting problem and I need to use this particular pseudo-code from the CLRS textbook. In it there two functions and one calls the other in this fashion
(r,s) = EXTENDED-BOTTOM-UP-CUT-ROD(p,n)
Where r and s are two different arrays. The function also returns two arrays. I am currently using C and I've tried things such as
(r,s)=function(p,n);
[r,s]=function(p,n);
{r,s}=function(p,n);
//return statements follow similar attempts
return (r,s);
return {r,s};
return [r,s];
All these typically resulted in errors or incorrect outputs. Perhaps I shouldn't be using basic arrays for this implementation?
CodePudding user response:
You can use tuples and "structured binding" in C 17 to return multiple values efficiently as below:
#include <tuple>
#invlude <vector>
std::tuple<std::vector<int>,std::vector<int>> func_that_returns_two_vectors() {
std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2 = {4, 5, 6};
return {std::move(v1), std::move(v2)};
}
int main() {
auto [v1, v2] = func_that_returns_two_vectors();
return 0;
}
To do something similar pre-C 17 you can use std::tie
.
CodePudding user response:
You can define your function to accept a
and b
by reference, and pass them in its call:
void func(...., vector<int>& a, vector<int>& b) {
// whatever manipulation on a and b.
}
vector<int> a;
vector<int> b;
func(..., a, b);
// changes will reflect on them.