Short
Short

Reputation: 7837

c++ std::copy input iterator (pointers) to vector

Hi I'm trying to understand why the following code does not work. I'm trying to use pointers as the input iterator type to the std::copy algorithm. fsRead.Buffer points to the beginning of the data I want to copy, and fsRead.BufferSize is size of the data that we want to copy.

// AllocateZeroPool(UINT64) takes an input size, and returns a pointer to allocated memory. (this is the existing C api)
fsRead.Buffer = static_cast<UINT8*>(AllocateZeroPool(fsRead.BufferSize));
//
// this next line populates the data into fsRead.Buffer
auto status = mFs->read_data(nullptr, &fsRead);

the type of file.data is: std::vector<UINT8>
std::copy(fsRead.Buffer, fsRead.Buffer + fsRead.BufferSize, file.data.begin());

file.data.size() is zero with the above std::copy() call.

To get the data into the vector file.data, I currently do the copy by hand:

for(auto i(0U); i < fsRead.BufferSize; ++i) {
    file.mBinaryData.emplace_back(fsRead.Buffer[i]);
}

Why does using two pointers as input iterators not seem to work?

edit: To clarify I mean that no data is actually copied into the file.mBinaryData vector.

Upvotes: 0

Views: 2250

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74098

With std::vector you must use a std::back_inserter. Without it the iterator will not do a push_back to copy the data, but just increment the given iterator.

std::copy(fsRead.Buffer, fsRead.Buffer + fsRead.BufferSize, std::back_inserter(file.data));

Upvotes: 4

Billy ONeal
Billy ONeal

Reputation: 106609

This fails because accessing iterators to a vector never change the size of the vector.

You can use one of the standard iterator adapters, such as back_inserter, to do this instead. That would look like this:

// Looks like you really wanted copy_n instead...
std::copy_n(fsRead.Buffer, fsRead.BufferSize, std::back_inserter(file.data));

Upvotes: 3

Related Questions