c++ - 如何使用按引用传递 C++ 将二维 vector 传递给函数

标签 c++ function structure 2d-vector

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

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

here is a screenshot of my error messege

最佳答案

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

使用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();
}

关于c++ - 如何使用按引用传递 C++ 将二维 vector 传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50188899/

相关文章:

c++ - 为什么普通的 C++ 编译器不优化掉对象拷贝?

php - 有没有一种 "conditional return"

python - 找到三个数字的中间

c++ - 双向链表总是只包含 1 条记录

mysql - 如何输出这种层次化的Mysql结构?

c - 受制于结构、获取和放置

c++ - 叮当格式 : disable ordering includes

c++ - protobuf-c 和 protobuf 的兼容性

c++ - 将结构写入文件会给我错误的结果

Javascript Mocha 测试 - 在函数表达式中测试函数表达式