c++ - 将作为参数传入的对象数组转换为 vector

标签 c++ vector iterator

<分区>

我正在尝试将 Wall 数组转换为 Wall vector 。该数组作为参数传入,在我尝试使用 insert() 转换它的函数中。我收到一条错误消息,指出“没有重载函数实例“std::begin”匹配参数列表——参数类型是:(Wall *)”

int func(int row, int col, Wall walls[]) {
  // Some code before ...

  // Converting array of Wall to vector
  std::vector<Wall> vecWalls;
  vecWalls.insert(vecWalls.begin(), std::begin(walls), std::end(walls));
 }

我试过在函数中创建另一个 Wall 数组并将其用作 insert() 的参数。然而,这并没有造成任何问题。

Wall walls2[5];
std::vector<Wall> vecWalls;
vecWalls.insert(vecWalls.begin(), std::begin(walls2), std::end(walls2));

当我的 Wall 数组作为参数传递时发生了什么。

最佳答案

参数 Wall walls[] 将衰减为 Wall *walls。由于您丢失了长度信息,因此您需要将该数组中的元素数量作为参数传递。像这样:

int func(int row, int col, Wall* walls, int len) {
    std::vector<Wall> vecWalls;
    vecWalls.insert(vecWalls.begin(), walls, walls + len);

    //or shorter:
    std::vector<Wall> vecWalls2(walls, walls + len);
}

关于c++ - 将作为参数传入的对象数组转换为 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58306422/

相关文章:

c++ - 使用 OpenCV 进行箭头形状检测

c++ - 除非明确专门化,否则模板类的静态成员不会实例化?

c++ - 在 C++ 中返回二维 vector 时出现段错误

委托(delegate)构造函数中的 C++ 大括号括起来的初始值设定项列表

一个列表理解中多个列表的Python值

c++ - 如何存储从 std::bind 返回的可调用对象以获取指向成员函数的指针?

c++ - 如何在C中使用空的main()方法运行函数?

c++ - STL vector : resize() and assign()

rust - 在具有可变生命周期的结构上实现迭代器时出错

c++ - 迭代器失效规则