gpt4 book ai didi

c++ - C++ 标准 11 实现的 std::move 函数

转载 作者:太空宇宙 更新时间:2023-11-04 05:36:29 31 4
gpt4 key购买 nike

我们都知道 C++ 标准 11 中实现的 std::move 函数的强大功能,它将特定范围内的元素移动到新范围内。

我想知道我是否可以用纯 C 代码开发这样的功能。我的代码是用 C 编写的,我希望有类似于 C++ 的 std::move 函数的东西,我可以在不使用临时缓冲区的情况下将整数元素的范围移动到新的范围。

最佳答案

关于您的文字:

... moves the elements in a specific range into a new range.

和:

... where I can move a range of integer elements into a new range without using a temporary buffer.

我认为您所追求的是memmove。它类似于 memcpy,但可以毫无问题地处理重叠区域。

例如,以下代码将元素从范围 3 到 6(从零开始)移动(实际上是复制)到范围 2 到 5:

#include <stdio.h>
#include <string.h>

int main (int argc, char *argv[]) {
int xyzzy[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
memmove (&(xyzzy[2]), &(xyzzy[3]), sizeof(*xyzzy) * 4);
printf ("{ %d", xyzzy[0]);
for (int i = 1; i < sizeof(xyzzy) / sizeof(*xyzzy); i++)
printf (", %d", xyzzy[i]);
printf (" }\n");

return 0;
}

基本上是这样的:

 {0 1 2 3 4 5 6 7 8 9}
| | | |
/ / / /
| | | |
V V V V
{0 1 3 4 5 6 6 7 8 9}

关于c++ - C++ 标准 11 实现的 std::move 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33820875/

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