如何将二维向量传递给 C++ 中的函数? [英] How to pass 2-D vector to a function in C++?

查看:26
本文介绍了如何将二维向量传递给 C++ 中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果是传递,是值传递还是引用传递?

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

推荐答案

自从你的函数声明:

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

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

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)

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.

这篇关于如何将二维向量传递给 C++ 中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆