开发者

Why doesn't std::generate return state similar to std::for_each?

开发者 https://www.devze.com 2023-03-28 11:32 出处:网络
std::generate returns void: te开发者_高级运维mplate<typename ForwardIterator, typename Generator>

std::generate returns void:

te开发者_高级运维mplate<typename ForwardIterator, typename Generator>
void generate(ForwardIterator first, ForwardIterator last, Generator gen);

While std::for_each returns Function:

template<typename InputIterator, typename Function>
Function for_each(InputIterator first, InputIterator last, Function f);

SGI's documentation suggests that for_each's result is useful for returning any state which may have mutated during the algorithm. Isn't the same true for generate? Is this an oversight, or is there a rationale for the difference in interface?


One significant difference is that whilst for_each operates on the container content, generate simply overwrites it. So the function object passed to generate can collect no information about the container content, so there'd be little reason to return it afterwards (its final state is invariant of the container content).


I suspect that it's to allow the predicate to be copied in generate's work so maintaining an internal state isn't always going to work right. for_each actually only mutates one instance of the predicate and then returns a copy of it.

When you usually do is have the predicate store a reference to an external state object and then check that when generate is done.

StateHolder state;
Generator generator(state); // Pass by reference.
std::generate(c.begin(), c.end(), generator);
// Now you can check the state object for whatever you need.
0

精彩评论

暂无评论...
验证码 换一张
取 消