0

我有几个浮点向量,我想将它们的字节复制到一个字节向量。实现这一目标的最佳方法是什么?迭代每个浮点向量,将浮点数转换为字节等等push_back()似乎buffer是一种低效的方式。

void CopyToByteVector(Vector<uint8_t>& buffer)
{
    Vector<float> vec1 = //....
    Vector<float> vec2 = //....

    // best way to copy byte values of vec1, vec2 into buffer?
}
4

2 回答 2

1

I don't think this is guaranteed to work, as far as the standard is concerned. I don't think there is a way to do what you are asking that is not undefined behavior. Having said that, I am near certain that , in almost all cases (and probably in absolutely all cases that you care about), it will work.

uint8_t * ibegin = reinterpret_cast<uint8_t*>(&vec1[0]);
auto size = vec1.size() * (sizeof(float)/sizeof(uint8_t));
buffer.assign(ibegin, ibegin + size);

// Not sure what you wanted to do with vec2. Append it?
ibegin = reinterpret_cast<uint8_t*>(&vec2[0]);
size = vec2.size() * (sizeof(float)/sizeof(uint8_t));
buffer.insert(buffer.end(), ibegin, ibegin + size);
于 2012-12-15T17:24:44.240 回答
0

std::vector有一个构造函数,它接受一对迭代器并将它们复制到向量中,您应该从查看它开始。

也不清楚“将浮点数转换为字节”是什么意思。是不是一塌糊涂?而且您的代码表明您的意图是完全相反的,向上浮动。

于 2012-12-15T17:01:12.733 回答