Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I write this pseudocode in C++? Function returns two arrays to two initialized arrays

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading