gpt4 book ai didi

c++ - STL std::remove_copy

转载 作者:行者123 更新时间:2023-11-30 03:27:27 28 4
gpt4 key购买 nike

 std::remove_copy

template <class InputIterator, class OutputIterator, class T>
OutputIterator remove_copy (InputIterator first, InputIterator last,
OutputIterator result, const T& val);

Copy range removing value, Copies the elements in the range [first,last) to the range beginning at result, except those elements that compare equal to val. The output container must be large enough to hold the result.

Q1。 为什么输出容器的大小必须足够大才能容纳结果?容器不会自己生长吗?

问题 2。 为什么当我执行 remove_copy 时输出容器中的先前内容被覆盖? 即当我执行 remove_copy(a.begin(),a.end(),b.begin() ,' '); 容器b中原来的内容丢失了,被新的内容代替了,为什么会这样呢?为什么 remove_copy 的结果没有追加到输出容器的开头?

最佳答案

Why the size of the output container must be large enough to hold the result? Wont the container grow by itself?

没有。怎么可能呢?所有的算法都是迭代器,你不能从它的迭代器访问容器的成员函数(这是容器增长所必需的)。然而,有一些特殊用途的迭代器知道如何增长容器。 std::front_insert_iterator , std::back_insert_iterator , 和 std::insert_iterator ,其中包含对容器的引用,并在取消引用和分配给它们时分别调用 push_frontpush_backinsert

Why is the previous content in the output container overwritten when i perform a remove_copy?

因为算法就是这样运作的。这就是所有标准库算法的工作原理。他们对容器一无所知。并非所有迭代器都来自容器。并不是所有的容器都可以生长。如果要附加到容器,请使用 std::back_insert_iterator,如上所述。您可以使用 std::back_inserter辅助函数,无需指定模板参数即可方便地创建一个。例如:

std::remove_copy(source.begin(), source.end(), std::back_inserter(dest), value);

关于c++ - STL std::remove_copy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47363115/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com