简体   繁体   中英

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

I need to convert std::vector buttonList to std::vector byteVector. I did it using this 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. I suspect that memcpy should not be used on vectors. 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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