how to convert std::vector to void*

前端 未结 1 826
耶瑟儿~
耶瑟儿~ 2021-02-19 08:01

I am wondering how can I convert std::vector to void*, for example:

std::vector pixels_ (w*h, background_         


        
相关标签:
1条回答
  • 2021-02-19 08:20

    To transform your vector into a void* type, there are two options:

    • Pre C++11: (void*)&pixels_[0] (!empty() check is recommended)
    • Since C++11: static_cast<void*>(pixels_.data())

    However, if you want to copy the elements, go straight with STL functions:

    • std::copy
    • std::uninitialized_copy

    They are type safe, your code looks much cleaner and the performance will be on par most of the times. Also, unlike std::memcpy, it also supports non-trivially copyable types (for example std::shared_ptr).

    Remember:

    We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%

    See TriviallyCopyable

    Update: since C++17 you can also use std::data, which will work for any container using contiguous memory storage (e.g. std::vector, std::string, std::array).

    ColorData* buffer = std::data(pixels_);
    
    0 讨论(0)
提交回复
热议问题