如何将二维向量传递给 C++ 中的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4061128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:25:40  来源:igfitidea点击:

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

c++vector2d

提问by bsoundra

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);

回答by casablanca

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:

指定一个指针,它本质上是通过引用传递的。但是,在 C++ 中,最好避免使用指针并直接传递引用:

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.

这看起来像一个普通的函数调用,但它是通过引用传递的,如函数声明中所示。这可以避免不必要的指针取消引用。

回答by Pablo Ruiz Ruiz

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);

回答by Benjamin Lindley

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.

您可以按值或按引用或按指针传递(不推荐)。如果要传递给不更改内容的函数,则可以按值传递,也可以按常量引用传递。我更喜欢 const 引用,有些人认为“正确”的方法是按值传递。

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

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

// to call
printMatrix(matrix1);