c++ - 如何使用传递引用 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);
}
我想通过引用在函数中传递一个二维向量,并将该向量与该函数中的另一个向量交换。但我收到错误。我不想用对向量来做。我想在这里使用结构。怎么做?
解决方案
一个主要问题:当传递一个数组作为参数时,真正传递的是一个指针。
它可以通过使用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();
}
推荐阅读
- python - SQLITE3 SELECT 语句不返回数据
- android - 在 Android 上设置全局代理 PAC
- docker - 使用 Mocha 和 Node 在 Docker 中进行 VSCode 调试
- websocket - 使用 Apache Camel AHC-WS Websocket 组件进行 JWT 不记名令牌身份验证
- google-apps-script - 脚本无法正确打开另一个电子表格
- c# - 通过 Winform 应用程序访问浏览器 LocalStorage
- android-studio - Android 虚拟设备组件
- java - 如何从 ArrayAdapter 列表开始新的片段?
- xslt - 如何使用“func:padStr 添加前导空格
- html - 如果 URL 以 / 结尾,则 .htaccess 中的 UTF-8 无效