简体   繁体   English

需要转换 std::vector<ButtonElement> buttonList 到 std::vector<BYTE> 字节向量

[英]Need to convert std::vector<ButtonElement> buttonList to std::vector<BYTE> byteVector

I need to convert std::vector buttonList to std::vector byteVector.我需要将 std::vector buttonList 转换为 std::vector byteVector。 I did it using this memcpy(&byteVector, &buttonList, buttonList.size() * sizeof(TenderButtonList_Element));我使用这个 memcpy(&byteVector, &buttonList, buttonList.size() * sizeof(TenderButtonList_Element));

But one of my seniors mentioned that it is not proper usage of STL but didn't say exactly what it is.但是我的一位前辈提到这不是 STL 的正确用法,但没有确切说明它是什么。 I suspect that memcpy should not be used on vectors.我怀疑 memcpy 不应该用于向量。 Is the above conversion valid, I observed that it served its purpose but wanted to know if it is valid or not.上述转换是否有效,我观察到它达到了目的,但想知道它是否有效。 If it isn't, can you point the correct way.如果不是,你能指出正确的方法吗?

If it isn't, can you point the correct way.如果不是,你能指出正确的方法吗?

That depends on what you are trying to accomplish.这取决于您要实现的目标。

You have a sequence (a vector ) of TenderButtonList_Element , right?你有一个TenderButtonList_Element的序列(一个vector ),对吧?

You're looking to produce a sequence of bytes containing the same bit pattern as the first sequence?您希望生成包含与第一个序列相同的位模式的字节序列? Is that correct?那是对的吗?

If that is what you're after, then you want something like this:如果这就是你所追求的,那么你想要这样的东西:

vector<std::byte> vBytes;
vBytes.resize(buttonList.size() * sizeof(TenderButtonList_Element));
memcpy(vBytes.data(), buttonList.data(), vBytes.size());

If you want something else, then you'll need to say what that is.如果你想要别的东西,那么你需要说那是什么。

Note that, in general, memcpy -ing c++ objects around does not produce valid objects.请注意,通常, memcpy -ing c++ 对象周围不会产生有效对象。

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

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