如何将 std::vector<vector> 转换为 void*
how to convert std::vector<vector> to void*
我想知道如何将 std::vector<vector>
转换为 void*
,例如:
std::vector<ColorData> pixels_ (w*h, background_color);
现在我想将 pixels_
转换为 void*
以便我可以 memcpy
pixels_
.
memcpy ((void*)destinationBuffer->pixels_, (void*)sourceBuffer->pixels_, \
sizeof(ColorData)*destinationBuffer->width_*destinationBuffer->height_);
但是当我 运行 这段代码时,我收到一条错误消息:
invalid cast from type ‘std::vector<image_tools::ColorData>’ to type ‘void*’
如何将 std::vector<vector>
转换为 void*
?
要将向量转换为 void*
类型,有两种选择:
- Pre C++11:
(void*)&pixels_[0]
(建议检查!empty()
)
- 自 C++11 起:
static_cast<void*>(pixels_.data())
但是,如果要复制元素,请直接使用 STL 函数:
它们是类型安全的,您的代码看起来更简洁,而且大多数情况下性能都差不多。此外,与 std::memcpy
不同,它还支持非平凡可复制类型(例如 std::shared_ptr
)。
记住:
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
).
ColorData* buffer = std::data(pixels_);
我想知道如何将 std::vector<vector>
转换为 void*
,例如:
std::vector<ColorData> pixels_ (w*h, background_color);
现在我想将 pixels_
转换为 void*
以便我可以 memcpy
pixels_
.
memcpy ((void*)destinationBuffer->pixels_, (void*)sourceBuffer->pixels_, \
sizeof(ColorData)*destinationBuffer->width_*destinationBuffer->height_);
但是当我 运行 这段代码时,我收到一条错误消息:
invalid cast from type ‘std::vector<image_tools::ColorData>’ to type ‘void*’
如何将 std::vector<vector>
转换为 void*
?
要将向量转换为 void*
类型,有两种选择:
- Pre C++11:
(void*)&pixels_[0]
(建议检查!empty()
) - 自 C++11 起:
static_cast<void*>(pixels_.data())
但是,如果要复制元素,请直接使用 STL 函数:
它们是类型安全的,您的代码看起来更简洁,而且大多数情况下性能都差不多。此外,与 std::memcpy
不同,它还支持非平凡可复制类型(例如 std::shared_ptr
)。
记住:
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
).
ColorData* buffer = std::data(pixels_);