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

标签 c++ arrays memory

我已经给出了类型为 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/

相关文章:

c++ - 只读取可变长度数组的长度,而不读取 hdf5 中的元素

c++ - 将 20 个数字输入到一个没有重复的数组中

c++ - 将 std::function 转换为不同的 std::function 并调用它?

ios - 如何将空值传递给数组?

c - 可能是内存问题还是其他什么问题?

c - 无法将我的共享内存的名称写入管道

c++ - 数据断点会影响Visual Studio中编译的代码吗?

javascript - 如何在Javascript中计算多个动态输入字段的总和?

c - 如何将字符串添加到C中的字符串数组

c# - 从内存中清除 C# 字符串