c++copystdvectorstdarraystdcopy

C++ How to copy a part of vector into array?


I was making a copy from a large dynamic array to a small fixed size array.

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

But I should use a vector instead of dynamic array. How to copy 16 bytes from vector into array?

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)
}

Solution

  • copy(dumpArr + i, dumpArr + i + 16, temp); // to copy 16 bytes from dynamic array
    

    can be written as

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

    and now the same code works for vector and array too.

    You can also use

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