Home > database >  C How to copy a part of vector into array?
C How to copy a part of vector into array?

Time:07-03

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

CodePudding user response:

You can use std::copy_n:

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

If you don't want to copy the first 16 elements, just step it forward:

std::copy_n(std::next(std::begin(vec), step), 16, std::begin(temp));

CodePudding user response:

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]);
  • Related