C++:将 2D 数组转换为 2D 向量

问题描述 投票:0回答:1

我想将 2D 数组 (faces0) 转换为 2D 向量 (faces1)。我尝试了以下代码。它给出了编译时错误。

bool read_polygon_mesh(Point_3 *points0,
    int **faces0,
    Polygon_mesh& polygon_mesh)
{
    std::vector<Point_3> points(points0, points0 + sizeof points0 / sizeof points0[0]);
    std::vector<std::vector<int>> faces1(faces0, faces0 + sizeof faces0 / sizeof faces0[0]);
    for (int i = 0; i < sizeof faces0 / sizeof faces0[0]; i++)
    {
        std::vector<int> f(faces0[i], faces0[i] + sizeof faces0[i] / sizeof faces0[i][0]);
        faces1.push_back(f);
    }

    return read_polygon_mesh(points, faces1, polygon_mesh);
}
c++ arrays pointers vector
1个回答
0
投票

在您的代码中

sizeof points0
不是数组的总大小,因为
points0
是指针,而不是数组,而是您必须将原始数组大小传递给函数。

bool read_polygon_mesh(Point_3 *points0, size_t num_points,
    int **faces0, size_t num_faces, size_t num_subfaces,
    Polygon_mesh& polygon_mesh)
{
    std::vector<Point_3> points(points0, points0 + num_points);
    std::vector<std::vector<int>> faces1(faces0, num_faces);
    for (int i = 0; i < num_faces; i++)
    {
        std::vector<int> f(faces0[i], faces0[i] + num_subfaces);
        faces1.push_back(f);
    }

    return read_polygon_mesh(points, faces1, polygon_mesh);
}

这显然是一个糟糕的设计,无法传递

size_t
,因此请考虑使用 std::span 来代替。

bool read_polygon_mesh(std::span<Point_3> points0,
    int **faces0, size_t num_faces, size_t num_subfaces,
    Polygon_mesh& polygon_mesh)
{
    std::vector<Point_3> points(points0, points0 + points0.size());
    std::vector<std::vector<int>> faces1(faces0, num_faces);
    for (int i = 0; i < num_faces; i++)
    {
        std::vector<int> f(faces0[i], faces0[i] + num_subfaces);
        faces1.push_back(f);
    }

    return read_polygon_mesh(points, faces1, polygon_mesh);
}

faces0
指向指针的指针可以展开到一个很长的跨度。

struct faces{
int* faces_ptr;
size_t num_rows;
size_t num_cols;
};

你可以将其传递到你的函数中。

© www.soinside.com 2019 - 2024. All rights reserved.