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


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


//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.

Leave a ReplyCancel reply