Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert std::vector<vector> to void*

Tags:

c++

stdvector

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

std::vector<ColorData> pixels_ (w*h, background_color);

Now I want to convert pixels_ to void* so that I can memcpy the pixels_.

memcpy ((void*)destinationBuffer->pixels_, (void*)sourceBuffer->pixels_, \
sizeof(ColorData)*destinationBuffer->width_*destinationBuffer->height_);
 

But when I run this code, I get an error which says:

invalid cast from type ‘std::vector<image_tools::ColorData>’ to type ‘void*’

How can I convert std::vector<vector> to void*?

like image 754
Xiufen Xu Avatar asked Nov 14 '16 17:11

Xiufen Xu


People also ask

Do you need to destruct a vector?

If you have a vector and it goes out of scope, all objects in the vector are destroyed. There isn't really a need to call clear() unless you want to dump the contents and reuse the vector.

How do I remove a string from a vector?

To remove all copies of an element from a vector , you can use std::remove like this: v. erase(std::remove(v. begin(), v.

How do you turn a vector into a string?

Convert Vector to String using toString() function To convert elements of a Vector to Strings in R, use the toString() function. The toString() is an inbuilt R function used to produce a single character string describing an R object.


1 Answers

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_);
like image 178
Jorge Bellon Avatar answered Sep 28 '22 04:09

Jorge Bellon