Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

c++11 - C++ standard wording: Does "through all iterators in the range" imply sequentiality?

This SO question sparked a discussion about std::generate and the guarantees made by the standard. In particular, can you use function objects with internal state and rely on generate(it1, it2, gen) to call gen(), store the result in *it, call gen() again, store in *(it + 1) etc., or can it start at the back, for example?

The standard (n3337, §25.3.7/1) says this:

Effects: The first algorithm invokes the function object gen and assigns the return value of gen through all the iterators in the range [first,last). The second algorithm invokes the function object gen and assigns the return value of gen through all the iterators in the range [first,first + n) if n is positive, otherwise it does nothing.

It seems like no ordering is guaranteed, especially since other paragraphs have stronger wording, for example std::for_each (Effects: Applies f to the result of dereferencing every iterator in the range [first,last), starting from first and proceeding to last - 1. If we're taking this literally, it only guarantees to start at first and end at last though - no guarantees on the ordering in between).

But: Both Microsoft's and Apache's C++ standard library both give examples on their documentation pages that require the evaluation to be sequential. And both libc++ (in algorithm) and libstdc++ (in bits/stl_algo.h) implement it that way. Moreover, you lose a lot of potential applications for generate without this guarantee.

Does the current wording imply sequentiality? If not, was this an oversight by the members of the committee or intentional?

(I am well aware that there aren't many people who can provide insightful answers to this question without merely speculating or discussing, but in my humble opinion, this does not make this question 'not constructive' as per SO guidelines.)


Thanks to @juanchopanza for pointing out this issue and referring me to the paragraph about for_each.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In the discussion of LWG475, std::for_each is compared with std::transform. It's noted that "transform does not guarantee the order in which its function object is called". So, yes, the committee is aware of the lack of sequential guarantees in the standard.

There is no opposite requirement for non-sequential behavior either, so Microsoft and Apache are free to use sequential evaluation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...