【问题标题】:c++ std::copy input iterator (pointers) to vectorc++ std::copy 输入迭代器(指针)到向量
【发布时间】:2013-01-14 17:41:48
【问题描述】:

您好,我想了解为什么以下代码不起作用。我正在尝试使用指针作为 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());

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

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

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

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

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

【问题讨论】:

  • 它“似乎不起作用”是什么意思?请描述错误...

标签: c++ vector iterator copy std


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    这会失败,因为访问向量的迭代器永远不会改变向量的大小。

    您可以改用其中一种标准迭代器适配器,例如back_inserter。看起来像这样:

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

    【讨论】:

    • 您能详细说明您提出的第一点吗? “这失败了,因为访问向量的迭代器永远不会改变向量的大小。”
    • @Short:这正是奥拉夫在回答中所说的——copy 就是destination++。在空的 vector 上增加 begin() 返回的值会导致未定义的行为,而不是更大的向量。
    猜你喜欢
    • 2014-10-13
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多