将一种数据类型的向量复制到同一数据类型的结构向量中的有效方法是什么

What is the efficient way to copy vectors of one data type into a vector of struct of the same data type?

本文关键字:数据类型 向量 结构 有效 方法 是什么 复制 一种      更新时间:2023-10-16

我有一个结构的向量,包含3个成员变量(vec3(pos(vec3将数据从独立向量转换为我上面提到的结构数据类型的向量,以便变量将根据结构中的变量对齐。我可以通过迭代向量的每个成员并分配变量来实现这一点,但是我正在寻找一种更快、更有效的方法,通过一个或两个函数调用将向量的整个范围复制到另一个向量,有这样的方法可以实现吗?

伪代码:

struct foo
{
vec3 pos;
vec3 norm;
vec2 texCoord;
}
vector<foo> attributes;
vector<vec3> x;
vector<vec3> y;
vector<vec2> z;
copy(x, attributes, offsetof(foo::pos), stride);
copy(y, attributes, offsetof(foo::norm), stride);
copy(z, attributes, offsetof(foo::texCoord), stride);

Hm,如果我们知道字节对齐,我们可能会做一些低级的脏东西。

但如果我们在更高的层面上坚持C++,我们就没有那么多可能性了。

这里有一些例子:

#include <iostream>
#include <vector>
#include <algorithm>
#include <vector>
#include <iterator>

using vec3 = int;
using vec2 = int;
struct foo
{
vec3 pos;
vec3 norm;
vec2 texCoord;
};
int main() {
std::vector<foo> attributes{};
std::vector<vec3> x{1,2,3};
std::vector<vec3> y{4,5,6};
std::vector<vec2> z{7,8,9};
// How many elements do we need to copy
size_t elementsToCopy {std::min({x.size(), y.size(), z.size()})};

// Solution 1 one. Straight forward. Emplace back and creation of temporary is slow
for (size_t i = 0; i < elementsToCopy; ++i)
attributes.emplace_back(foo {x[i],y[i],z[i]});

// Solution 2. Slight improvement. Set initial size of target vector. Then copy in simple loop. Creation of temporary is slow
attributes.resize(elementsToCopy);
for (size_t i = 0; i < elementsToCopy; ++i)
attributes[i] = std::move(foo ({x[i],y[i],z[i]}));
// Wrapping in algorithm. But no real improvement. More a less just obfuscation
std::for_each(attributes.begin(), attributes.end(), [i=0U, &x,&y,&z](foo &f) mutable { return std::move(foo ({x[i],y[i],z[i]}));++i;} );
for (const auto a : attributes)   
std::cout << a.pos << " " << a.norm << " " << a.texCoord << "n";
return 0;
}

我认为,现有的算法在这里不会有太大帮助。我们可以写一个lambda或函数。但这会使代码更漂亮,但不会更快。

我认为3个向量x,y,z也有一个缺陷。它们可以有任何大小。

也许为structfoo添加成员函数是一个更安全的解决方案。有些添加了功能或类似功能。

但不幸的是,我没有理想的解决方案。