C++如何将矢量的一部分复制到数组中



我正在从一个大的动态数组复制到一个小的固定大小数组。

for (int i = 0; i <= dumpVec.size() - 16; i++)
{
copy(dumpArr + i, dumpArr + i + 16, temp); // to copy 16 bytes from dynamic array
}

但是我应该使用向量而不是动态数组。如何将矢量中的16个字节复制到数组中?

for (int i = 0; i <= dumpVec.size() - 16; i++)
{
array<byte, 16> temp;
// place to copy each 16 bytes from dumpVec(byte vector) into temp(byte array)
}

您可以使用std::copy_n:

std::vector<int> vec(/* large number */);
std::array<int, 16> temp;
std::copy_n(std::begin(vec), 16, std::begin(temp));

如果你不想复制前16个元素,只需向前推进:

std::copy_n(std::next(std::begin(vec), step), 16, std::begin(temp));
copy(dumpArr + i, dumpArr + i + 16, temp); // to copy 16 bytes from dynamic array

可以写成

copy(&dumpArr[i], &dumpArr[i + 16], &temp[0]); // to copy 16 bytes from dynamic array

现在相同的代码也适用于CCD_ 2和CCD_。

你也可以使用

copy_n(&dumpArr[i], 16, &temp[0]);

最新更新