I'm trying to create a function that transposes a matrix in the form of a vector array. The program almost works, except that the first 2 values of the new vector returns these large numbers instead of the values given to them. It seems to be a problem with the returning process, as when I outputted the values in the function everything was fine.
The matrix vector that you create in the matrixTransposer will go out of scope when the function ends so what will be returned is a pointer to a non-existing vector. It's better to simply return the vector by value. You don't need to worry about this being inefficient. Returning a local variable will be optimized so that it doesn't need to do a full copy of the vector when you return it.
1 2 3 4 5
vector<int> matrixTransposer(vector<int> * matrixPointer, int r, int c)
{
...
return matrix;
}
There is no point in creating a vector and then resizing it if you are going to assign (copy) another vector to it in the line below. Just initialize the vector with the return value of the function directly.
You don't really need to use a pointer in the function at all. The vector that the pointer points to will always be copied anyway so why not simply make the matrix variable the parameter and have it copied directly. This is also better because it prevents anyone from passing a null pointer to the function (it also avoids copying in case you pass an rvalue-reference to the function).
vector<int> matrixTransposer(vector<int> matrix, int r, int c);
If you make this change the vector is passed as-is, without using a pointer.