简体   繁体   中英

Retuning multiple vectors from a function in c++?

I want to return multiple vectors from a function. I am not sure either tuple can work or not. I tried but is not working.

xxx myfunction (vector<vector<float>> matrix1 , vector<vector<float>> matrix2) {

// some functional code: e.g. 
// vector<vector<float>> matrix3 = matrix1 + matrix2;
// vector<vector<float>> matrix4 = matrix1 - matrix2;

return matrix3, matrix4;

If these matrices are very small then this approach might be OK, but generally I would not do it this way. First, regardless of their size, you should pass them in by const reference.

Also, std::vector<std::vector<T>> is not a very good "matrix" implementation - much better to store the data in a contiguous block and implement element-wise operations over the entire block. Also, if you are going to return the matrices (via a pair or other class) then you'll want to look into move semantics as you don't want extra copies.

If you are not using C++11 then I'd pass in matrices by reference and fill them in the function; eg

using Matrix = std::vector<std::vector<float>>; // or preferably something better

void myfunction(const Matrix &m1, const Matrix &m2, Matrix &diff, Matrix &sum)
{
    // sum/diff clear / resize / whatever is appropriate for your use case
    // sum = m1 + m2
    // diff = m1 - m2
}

The main issue with functional style code, eg returning std::tuple<Matrix,Matrix> is avoiding copies. There are clever things one can here to avoid extra copies but sometimes it is just simpler, IMO, to go with a less "pure" style of coding.

For Matrices, I normally create a Struct or Class for it that has these vectors, and send objects of that class in to the function. It would also help to encapsulate Matrix related operations inside that Class.

If you still want to use vector of vector, here is my opinion. You could use InOut parameters using references/pointers : Meaning, if the parameters can be updated to hold results of calculation, you would be sending the arguments in, and you would not have to return anything in that case.

If the parameters need to be const and cannot be changed, then I normally send In parameters as const references, and separate Out parameters in the function argument list itself.

Hope this helps a bit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM