5 c++ arrays algorithm stdvector c++17
我有两个数组
float vertices[] = {
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
0.0f, 0.5f, 0.0f
};
float normals[] = {
0.0, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f
};
Run Code Online (Sandbox Code Playgroud)
我首先想将vertices数组添加到 a std::vector<float>,然后将normals数组插入向量。
我能想到的是运行一个基于 的循环sizeof(Array)并将单个元素推回向量。
当我访问它们时,这能保证插入的值按正确的顺序排列吗?
您可以将std::vector::insert元素放在向量的末尾。
#include <iterator> // std::cbegin, std::cend, std::size
#include <vector>
std::vector<float> vec;
// reserve the memory for unwated reallocations.
vec.reserve(std::size(vertices) + std::size(normals));
vec.insert(vec.end(), std::cbegin(vertices), std::cend(vertices));
vec.insert(vec.end(), std::cbegin(normals), std::cend(normals));
Run Code Online (Sandbox Code Playgroud)
[...]基于 运行循环
sizeof(Array)并将单个元素推回向量。当我访问它们时,这是否能保证插入的值按正确的顺序排列?
确实是的。请记住,如果您可以使用c++17或更高版本的编译器,则可以使用std::size来查找数组的大小。