Take, for example, std::generate() and std::generate_n() . The former accepts ForwardIterator s, indicating the beginning and end of the range, the latter a OutputIterator . This has minor consequences, for example:
#include <algorithm> #include <vector> int main() { std::vector<int> v; v.resize(5); // <-- Elements constructed!!! std::generate(v.begin(), v.end(), [](){ return 42; }); std::vector<int> w; w.reserve(5); // Space only reserved but not initialized std::generate_n(std::back_inserter(w), 5, [](){ return 42; }); }
This is enough to justify the existence of two versions.
You are absolutely right that in many cases the functionality of these functions overlaps, and one of them may look superfluous.
why only these algorithms?
Probably because no one has offered the _n version for other algorithms yet. Like TemplateRex , maybe std::iota_n() : What would be a good implementation of iota_n (there is no algorithm from STL) ?
Ali
source share