Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no std::move_n algorithm?

Tags:

c++

c++17

I'm assuming that there is a std::copy_n so that this can work with input iterators. Is there some reason why there is no std::move_n for the same reason?

like image 598
Adrian Avatar asked Apr 03 '19 18:04

Adrian


2 Answers

I think the answer is probably pretty mundane.

std::copy existed forever, it was the only one of these algorithms in C++03.

N1377 (2002) added move semantics into the language and also introduced the algorithms std::move() and std::move_backward() to mirror the existing std::copy() and std::copy_backward(). Those were the only copying algorithms in existence - so those were the only ones that got move versions.

N2569 (2008) added a bunch more algorithms, most of which existed in the original Standard Template Library implementation - this is where std::copy_n() and std::copy_if() came from. Since the premise of the paper was a bunch of algorithms that have been around and used for years, it couldn't have included std::move_n() or std::move_if(). It seems that this simply wasn't considered.

I'm guessing if these happened in the opposite order, we might have had std::move_n() today. But at this point, it might not be worth adding. Since, std::copy_n() isn't even used super often and move_n is very easy to implement:

template< class InputIt, class Size, class OutputIt>
OutputIt move_n(InputIt first, Size count, OutputIt result)
{
    return std::copy_n(std::make_move_iterator(first), count, result);
}
like image 137
Barry Avatar answered Sep 22 '22 23:09

Barry


There is a std::make_move_iterator to adapt any iterator into providing an rvalue.

Sending an adapted input iterator to std::copy_n will achieve the desired effect, without much added noise.

like image 34
StoryTeller - Unslander Monica Avatar answered Sep 25 '22 23:09

StoryTeller - Unslander Monica