Why is there no std::move_if algorithm?

邮差的信 提交于 2019-12-05 15:18:38

If move_if existed as an algorithm, it would have to be specified as:

template <class InputIt, class OutputIt, class UnaryPredicate>
OutputIt move_if(InputIt first, InputIt last, OutputIt d_first, UnaryPredicate pred)
{
    return std::copy_if(std::make_move_iterator(first), std::make_move_iterator(last),
        d_first, pred);
}

We are very used to thinking of the difference between copying and moving as simply a matter of whether or not we care about the source object. We still do? Copy. We don't? Move. Having move_if(f, l, d, pred) do something semantically different than copy_if(f, l, d, pred) seems inherently confusing and error-prone - since the inevitable usage of it would be to do a "copy where we don't care about the source anymore."

But then - you're more or less describing the problems with this algorithm in your question. When would I use this? I would end up with a source range where some of the elements are moved-from but others aren't. What could I do with such a range? I couldn't coalesce them somehow since I don't know which ones they are or anything. Moving those elements to the back is useful - and we do have that algorithm: remove_if.

Basically the only thing I could do with the source range at this point is destroy it. Maybe that's useful. Maybe that's useful enough to even merit this algorithm in std::. I don't know. But move_if definitely needs to do the same thing as copy_if.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!