简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM