gpt4 book ai didi

C++如何在不复制数据的情况下添加和到数组?

转载 作者:行者123 更新时间:2023-11-30 02:26:06 25 4
gpt4 key购买 nike

我已经给出了类型为 uint8_t[n] 的数据缓冲区。现在我必须向这个数组添加一个 head,即 uint8_t 之前的一个值。但是我不想 memcpy 数据!

给定数组:

0x0800 - Start of data buffer
...
0x0900 - End of data buffer

新数组:

0x07ff - Head
0x0800 - Start of data buffer
...
0x0900 - End of data buffer

有没有可能这样做或者内存分配有问题?

最佳答案

如果不移动内存对您来说很重要,那么 std::deque可以为你做到这一点:

std::deque (double-ended queue) is an indexed sequence container that allows fast insertion and deletion at both its beginning and its end. In addition, insertion and deletion at either end of a deque never invalidates pointers or references to the rest of the elements.

As opposed to std::vector, the elements of a deque are not stored contiguously: typical implementations use a sequence of individually allocated fixed-size arrays, with additional bookkeeping, which means indexed access to std::deque must perform two pointer dereferences, compared to vector's indexed access which performs only one.

The storage of a deque is automatically expanded and contracted as needed. Expansion of a deque is cheaper than the expansion of a std::vector because it does not involve copying of the existing elements to a new memory location. On the other hand, deques typically have large minimal memory cost; a deque holding just one element has to allocate its full internal array (e.g. 8 times the object size on 64-bit libstdc++; 16 times the object size or 4096 bytes, whichever is larger, on 64-bit libc++).

关于C++如何在不复制数据的情况下添加和到数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43300401/

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