且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C++:从vector<vector<T>>得到T**

更新时间:2021-08-10 01:12:42

您可以创建一个新的 vector,其中包含指向由内部 vector 管理的所有内部数组的指针你的向量向量:

You could create a new vector holding the pointers to all the internal arrays managed by the inner vector of your vector of vectors:

void old_c_function(float** floats, std::size_t X, std::size_t Y)
{
    for(auto x = 0U; x < X; ++x)
        for(auto y = 0U; y < Y; ++y)
            std::cout << "[" << x << ", " << y << "] = " << floats[x][y] << '\n';
}

int main()
{
    std::vector<std::vector<float>> v =
    {
        {1.2, 3.4, 5.6},
        {7.8, 9.0, 1.2},
    };

    // create a new vector to hold the pointers to the arrays
    // managed by the internal vectors
    std::vector<float*> v_ptrs;
    v_ptrs.reserve(v.size());

    // add the addresses of all the arrays to the new vector
    std::for_each(std::begin(v), std::end(v),
        [&v_ptrs](auto& v){ v_ptrs.push_back(v.data()); });

    // call your legacy function using your pointer vector
    old_c_function(v_ptrs.data(), v.size(), v.front().size());
}

输出:

[0, 0] = 1.2
[0, 1] = 3.4
[0, 2] = 5.6
[1, 0] = 7.8
[1, 1] = 9
[1, 2] = 1.2

注意:

显然,如果您更改向量,则需要重建指针向量,因为地址很可能会更改.

Obviously if you change your vector you will need to rebuild your pointer vector because the addresses may well change.

您可以通过一些包装函数即时重建它,如下所示:

You can either rebuild it on the fly through some wrapper function like so:

void new_wrapper_function(std::vector<std::vector<float>>& v)
{
    // create a new vector to hold the pointers to the arrays
    // managed by the internal vectors
    std::vector<float*> v_ptrs;
    v_ptrs.reserve(v.size());

    // add the addresses of all the arrays to the new vector
    std::for_each(std::begin(v), std::end(v)
        [&v_ptrs](auto& v){ v_ptrs.push_back(v.data()); });

    // call your legacy function using your pointer vector
    old_c_function(v_ptrs.data(), v.size(), v.front().size());
}

或者(我最喜欢的)构建一个包装器 class 来封装两个向量,并在主要向量在其维度中的容量增加时更新指针向量.

Or else (my favorite) build a wrapper class to encapsulate both vectors and update the pointer vector whenever the primary vector increases in capacity in one of its dimensions.