[英]std::vector<char> into std::vector<T> conversion c++
I want to create a std::vector<T>
of length len
from serialized data contained in a std::vector<char>
of length len * (sizeof T)
, without copying data when not necessary (it may not be possible for, eg, align requirements of T
). 我想从长度为len * (sizeof T)
的std::vector<char>
中包含的序列化数据创建长度为len
的std::vector<T>
,在没有必要的情况下不复制数据(对于,例如,对齐要求T
)。 In other words I look for an optimization of the following code, operating on the same guarantees: 换句话说,我正在寻找以下代码的优化,并在相同的保证下运行:
template<typename T>
auto copyStuff(std::vector<char>&&input) {
std::vector<T> result;
result.resize(input.size()/(sizeof T));
for (int i=0; i < result.size(); i++) {
memcpy(&result[i], &input[i * (sizeof T)], sizeof T);
}
return result;
}
which 哪一个
memcpy
call if possible 否则,如果可能,在一次memcpy
调用中复制所有字节 Is there a standard way, or a portable library, to achieve this (or a "good enough" approximation)? 是否有标准方法或可移植库来实现这一目标(或“足够好”的近似值)?
Clarifications: 说明:
T
is trivially copiable, and the layout of the input std::vector<char>
is simply the concatenation of the memory representation of the item which I want to construct. 我只需要假设T
是可微复制的,输入std::vector<char>
的布局就是我要构造的项的内存表示形式的串联。 vector
s) if they offer this low overhead type punning. 我愿意考虑非标准容器库(而不是vector
),如果它们提供这种低开销的类型修剪。 It is not possible to get vector of one type from another type without copying. 如果没有复制,则不可能从另一种类型中获得一种类型的向量。
You can avoid one set of copies by constructing the vector of T
(of sufficient size) initially, and then writing the serialized data directly onto that vector without the use of an intermediate vector of chars. 通过首先构造T
(足够大)的向量,然后不使用chars的中间向量,直接将序列化的数据写入该向量,就可以避免一组副本。
A few caveats: 一些警告:
T
must be trivially copyable type. T
必须是平凡可复制的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.