gpt4 book ai didi

c++ - 是否有与 memmove 等效的标准库?

转载 作者:行者123 更新时间:2023-12-05 02:41:34 26 4
gpt4 key购买 nike

标准库提供了std::copy,可以看作是C的memcpy()的泛化/类化。它还保持了 memcpy() 的要求,范围 [first, last) 与范围 [d_first , d_first + std::distance(first, last));否则我们有未定义的行为。

我的问题:是否有 std::memmove 的通用版本(即不满足该要求且通常使用临时缓冲区实现)?如果不是,怎么会?

最佳答案

C++ 没有减少 memcpy 的替代品和 memmove .

对于非重叠范围,通常为 std::copy使用,但 std::copy_backwards也可以使用。

对于重叠范围,您需要使用 std::copystd::copy_backwards取决于重叠的性质。

也适用于复制昂贵的对象 std::move ( <algorithm> ) std::move_backward 如果原始对象不需要保留其值,则可以分别使用。

std::copy

template< class InputIt, class OutputIt >
OutputIt copy( InputIt first, InputIt last, OutputIt d_first );

Copies the elements in the range, defined by [first, last), to anotherrange beginning at d_first.

Copies all elements in the range [first, last) starting from first andproceeding to last - 1. The behavior is undefined if d_first is withinthe range [first, last). In this case, std::copy_backward may be usedinstead.

Notes
When copying overlapping ranges, std::copy is appropriate when copyingto the left (beginning of the destination range is outside the sourcerange) while std::copy_backward is appropriate when copying to theright (end of the destination range is outside the source range).

std::copy_backward

template< class BidirIt1, class BidirIt2 >
BidirIt2 copy_backward( BidirIt1 first, BidirIt1 last, BidirIt2 d_last );

Copies the elements from the range, defined by [first, last), toanother range ending at d_last. The elements are copied in reverseorder (the last element is copied first), but their relative order ispreserved.

The behavior is undefined if d_last is within (first, last]. std::copymust be used instead of std::copy_backward in that case.

Notes
When copying overlapping ranges, std::copy is appropriate when copying to the left (beginning of the destinationrange is outside the source range) while std::copy_backward isappropriate when copying to the right (end of the destination range isoutside the source range).

关于c++ - 是否有与 memmove 等效的标准库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68050977/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com