0

Currently, my code is something like this:

vector<vector<string>> result;

for (Example e : someExampleIterable) {
    result = e.evaluate(result);
}

// Do some operations with the result later

vector<vector<string>> Example::evaluate(vector<vector<string>> intermediate) {
    vector<vector<string>> result;
    vector<vector<string>> newTable = someExternalAPI.get(someAttributeOfThisObject);    

    for (vector<string> row : intermediate) {
        // Some complex operation that combines and manipulates data from newTable & intermediate
        result.push_back(final_data);
    }

    return result;
}

As you can see what I'm trying to achieve is like a "pipeline" sort of loop where I constantly update my result.

Since my function that manipulates the existing table involves creating a new table and returning it due to the complex operations done with the newTable and intermediateTable (plus this is how I coded it to have this pipeline), is there a way where I can use references so that I do not have to keep on shallow copying my vector<vector> which I understand is expensive in C++, especially since my intermediate can be quite large.

Would changing the function definition to the below work even with the reassigning? Or what is the best practice for this kind of pipelining kind of loop.

vector<vector<string>> Example::evaluate(vector<vector<string>>& intermediate)

If possible, I would want to do a:

void Example::evaluate(vector<vector<string>>& intermediate)

where I can manipulate my intermediate table directly but as mentioned, the operations are quite complex and it would be easier to do on a new empty table and return it.

Thanks!

kohrhea
  • 159
  • 7
  • 2
    References cannot be reassigned beyond initialization. – πάντα ῥεῖ Oct 20 '22 at 17:02
  • Either of the two alternatives could work fine, because you're not actually reassign any references. – Some programmer dude Oct 20 '22 at 17:02
  • Also, modern compilers are good at eliding copying of returned values, though that might not be possible in this case. But passing the vector argument `intermediate` by reference will increase performance a bit. I also recommend e.g. `for (auto const& row : intermediate)` to use more references and even less copying. Do something similar with the earlier loop where you call `evaluate`. – Some programmer dude Oct 20 '22 at 17:06
  • Thanks for the comments! Just want to check for my above example, this means I'm just changing the value of my reference (memory address stays the same) to the result I'm returning, so there won't be any issues with passing the intermediate as a reference right? Is this similar to a `x = x+y` scenario, where the x is my intermediate in a way? Apologies as I'm new with C++ so this is a bit new to me – kohrhea Oct 20 '22 at 17:53

0 Answers0