[英]How to pass a 2D vector to a function using pass-by-reference C++
struct st
{
int to, cost;
};
void fun(vector<st>&v1[10])
{
vector<st>v2[10];
v1=v2;
}
int main()
{
vector<st>arr[10];
fun(arr);
}
我想通过引用在函数中传递2D向量,并将该向量与该函数中的另一个向量交换。 但是我遇到了错误。 我不想对向量。 我想在这里使用结构。 怎么做?
一个主要问题:当将数组作为参数传递时,真正传递的是指针 。
可以通过使用std::array
轻松解决:
void fun(std::array<std::vector<st>, 10>& v1)
{
std::array<std::vector<st>, 10> v2;
// Initialize v2...
v1 = v2;
}
int main()
{
std::array<std::vector<st>, 10> arr;
fun(arr);
}
在上面介绍了std::array
之后,我宁愿建议返回数组而不是通过引用传递:
std::array<std::vector<st>, 10> fun()
{
std::array<std::vector<st>, 10> v2;
// Initialize v2...
return v2;
}
int main()
{
std::array<std::vector<st>, 10> arr = fun();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.