如何在 std 向量中推送数组

Fre*_*ios 1 c++ vector

我正在 OpenGL 中做一些高度图。每个顶点的唯一 z 存储在一个文件中,我还必须将 x 和 y 值存储在一个向量中:

#include <vector>
#include <fstream>
#include <sstream>

int main(void)
{
    std::vector<float>      _data;
    float constexpr         triangle_side(1.118033989);
    std::ifstream           ifs("mymap");
    std::string             line;

    if (not ifs.is_open())
        return -1;
    for (float y(0) ; std::getline(ifs, line) ; --y)
    {
        std::istringstream  iss(line);

        for (float x(static_cast<int>(y) % 2 ? 0 : triangle_side / 2), z ; iss >> z ; x += triangle_side)
            _data.push_back({x, y, z}); // does not compile
    }
    ifs.close();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在我看来,这是一件坏事:_data.push_back(x); _data.push_back(y); _data.push_back(z);因为向量可能会在每次调用时重新分配数组。

最好的方法是什么?

如果我做 :

std::vector< std::array<float, 3> > _data;
//...
_data.push_back({x, y, z});
Run Code Online (Sandbox Code Playgroud)

是否保证这些值都是连续的?

Sim*_*ple 6

std::array<float, 3>像内存中的 C 数组一样布局,因此floats 将是连续的。你也可以只使用insert

_data.insert(_data.cend(), {x, y, z});
Run Code Online (Sandbox Code Playgroud)