C++ std::copy 输入迭代器(指针)到 vector

标签 c++ vector iterator copy std

您好,我想了解为什么以下代码不起作用。我正在尝试使用指针作为 std::copy 算法的输入迭代器类型。 fsRead.Buffer 指向我要复制的数据的开头,fsRead.BufferSize 是我们要复制的数据的大小。

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

在上述 std::copy() 调用中,file.data.size() 为零。

为了将数据放入 vector file.data 中,我目前手动进行复制:

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

为什么使用两个指针作为输入迭代器似乎不起作用?

编辑:澄清一下,我的意思是实际上没有数据被复制到 file.mBinaryData vector 中。

最佳答案

对于 std::vector,您必须使用 std::back_inserter .没有它,迭代器将不会执行 push_back 来复制数据,而只会递增给定的迭代器。

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

关于C++ std::copy 输入迭代器(指针)到 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14323674/

相关文章:

c++ - 在非静态成员函数中使用 C++11 lambda 并调用同一类的静态成员函数

c++ - 嵌套类的替代方案

vector - 函数如何将值附加到向量并返回该值?

c++ - 将 pop_front 实现为 std::vector 的快速方法

迭代整数位的 Pythonic 方法

c++ - 在 C++ 中, "const_iterator"与 "const iterator"相同吗?

c++ - 向现有 XML 文档添加节点

c++ - dll/bundle 中的单例生命周期

c++ - 使用 const 成员分配类

Java - 具有递归方法和嵌套迭代器的 ConcurrentModificationException