How to pass 2-D vector to a function in C++?

十年热恋 提交于 2019-12-03 17:01:52

问题


If it is passed, is it passed by value or by reference?

void printMatrix(vector<vector<int>> *matrix);

...

vector<vector<int>> matrix(3, vector<int>(3,0));
printMatrix(&matrix1);

回答1:


Since your function declaration:

void printMatrix(vector< vector<int> > *matrix)

specifies a pointer, it is essentially passed by reference. However, in C++, it's better to avoid pointers and pass a reference directly:

void printMatrix(vector< vector<int> > &matrix)

and

printMatrix(matrix1); // Function call

This looks like a normal function call, but it is passed by reference as indicated in the function declaration. This saves you from unnecessary pointer dereferences.




回答2:


Well, first of all, you're creating it wrong.

vector<vector<int>> matrix1(3, vector<int>(3,0));

You can pass by value or by reference, or by pointer(not recommended). If you're passing to a function that doesn't change the contents, you can either pass by value, or by const reference. I would prefer const reference, some people think the "correct" way is to pass by value.

void printMatrix(const vector<vector<int>> & matrix);

// or
void printMatrix(vector<vector<int>> matrix);

// to call
printMatrix(matrix1);



回答3:


Why not passing just the 2d vector?

void printMatrix(vector < vector<int> > matrix)
{
    cout << "[";
    for(int i=0; i<matrix.size(); i++)
    {
        cout << "[" << matrix[i][0];
        for(int j=0; j<matrix[0].size(); j++)
        {
            cout  << ", " << matrix[i][j];
        }
        cout << "]" << endl;
    }
    cout << "]" << endl;
}

vector < vector<int> > twoDvector;
vector<int> row(3,2);

for(int i=0; i<5; i++)
{
    twoDvector.push_back(row);
}

printMatrix(twoDvector);


来源:https://stackoverflow.com/questions/4061128/how-to-pass-2-d-vector-to-a-function-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!