首页 > 解决方案 > 如何使用传递引用 C++ 将 2D 向量传递给函数

问题描述

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

我想通过引用在函数中传递一个二维向量,并将该向量与该函数中的另一个向量交换。但我收到错误。我不想用对向量来做。我想在这里使用结构。怎么做?

这是我的错误消息的屏幕截图

标签: c++functionstructure2d-vector

解决方案


一个主要问题:当传递一个数组作为参数时,真正传递的是一个指针

它可以通过使用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();
}

推荐阅读