简体   繁体   English

如何在标准向量中推送数组

[英]How to push an array in a std vector

I am doing some height map in OpenGL. 我在OpenGL中做一些高度图。 The only z of each vertex is stored in a file, and I have to store as well the x and y value in a vector : 每个顶点的唯一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;
}

In my opinion, it is a bad thing to do : _data.push_back(x); _data.push_back(y); _data.push_back(z); 我认为这是一件坏事: _data.push_back(x); _data.push_back(y); _data.push_back(z); _data.push_back(x); _data.push_back(y); _data.push_back(z); because the vector perhaps will reallocate the array at each call. 因为向量可能会在每次调用时重新分配数组。

What is the best way to do it ? 最好的方法是什么?

If I do : 如果我做 :

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

is it guaranteed the values will all be contiguous ? 是否保证所有值都是连续的?

std::array<float, 3> is laid out like a C array in memory, so the float s will be contiguous. std::array<float, 3>的布局类似于C数组在内存中的位置,因此float s是连续的。 You could also just use insert : 您也可以只使用insert

_data.insert(_data.cend(), {x, y, z});

Use std::vector::reserve(size_type n) to reserve that the backing array contain at least n elements. 使用std :: vector :: reserve(size_type n)保留后备数组至少包含n个元素。 If it does not, it will be reallocated once. 如果没有,它将被重新分配一次。 On an existing vector, if you need not just '3' but 'at least 3 more' elements, you just call it with (std::vector::size + 3). 在现有向量上,如果您不仅需要'3',而且还需要'至少3个以上'元素,则只需使用(std :: vector :: size + 3)进行调用。 After that you can push back safely with the guarantee the array won't be reallocated inside the vector. 之后,您可以放心地向后推,确保不会在向量内重新分配数组。

A vector of std::array is forced to be contiguous by the standard, as is std::vector. 标准将std :: array的向量强制为连续的,就像std :: vector一样。 A std::vector of std::arrays thus has all the elements in contiguous order. 因此,std :: arrays的std :: vector具有所有相邻元素。 Source 资源

@cin_cout: C++03 (23.2.4.1): @cin_cout:C ++ 03(23.2.4.1):

The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size(). 向量的元素是连续存储的,这意味着如果v是向量,其中T是非bool的某种类型,则它对所有0 <= n <v都服从&v [n] ==&v [0] + n的标识。尺寸()​​。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM