如何转换 std::vector<vector>作废* [英] how to convert std::vector<vector> to void*
问题描述
我想知道如何将 std::vector
转换为 void*
,例如:
I am wondering how can I convert std::vector<vector>
to void*
, for example:
std::vector<ColorData> pixels_ (w*h, background_color);
现在我想将 pixels_
转换为 void*
以便我可以 memcpy
pixels_
.>
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:
从类型‘std::vector
invalid cast from type ‘std::vector<image_tools::ColorData>’ to type ‘void*’
如何将 std::vector
转换为 void*
?
推荐答案
要将向量转换为 void*
类型,有两个选项:
To transform your vector into a void*
type, there are two options:
- Pre C++11:
(void*)&pixels_[0]
(推荐使用!empty()
检查) - 自 C++11 起:
static_cast
(pixels_.data())
- Pre C++11:
(void*)&pixels_[0]
(!empty()
check is recommended) - Since C++11:
static_cast<void*>(pixels_.data())
但是,如果您想复制元素,请直接使用 STL 函数:
However, if you want to copy the elements, go straight with STL functions:
它们是类型安全的,您的代码看起来更简洁,而且大多数时候性能都相当.此外,与 std::memcpy
不同的是,它还支持非平凡的可复制类型(例如 std::shared_ptr
).
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
).
记住:
我们应该忘记小效率,比如大约 97% 的时间:过早优化是万恶之源.然而,我们不应该在关键的 3% 中放弃我们的机会
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%
更新:从 C++17 开始,你也可以使用 std::data
,它适用于任何使用连续内存存储的容器(例如 std::vector
、std::string
、std::array
).
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_);
这篇关于如何转换 std::vector<vector>作废*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!