Is it defined to provide an inverted range to C++ standard algorithms?

后端 未结 5 648
南旧
南旧 2021-01-17 19:29

Consider standard algorithms like, say, std::for_each.

template
Function for_each(InputIterator first         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-17 19:59

    The result is Undefined.


    C++03 Standard: 25.1.1 For each and
    C++11 Standard: 25.2.4 For each states:

    template
    Function for_each(InputIterator first, InputIterator last, Function f);
    

    1 Effects: Applies f to the result of dereferencing every iterator in the range [first, last), starting from first and proceeding to last - 1

    While another section defines the valid range [first,last) as:

    C++03 Standard: 24.1 Iterator requirements and
    C++11 Standard: 24.2.1 Iterator requirements

    Para 7 for both:

    Most of the library’s algorithmic templates that operate on data structures have interfaces that use ranges.A range is a pair of iterators that designate the beginning and end of the computation. A range [i, i) is an empty range; in general, a range [i, j) refers to the elements in the data structure starting with the one pointed to by i and up to but not including the one pointed to by j. Range [i, j) is valid if and only if j is reachable from i. The result of the application of functions in the library to invalid ranges is undefined.


    Having remembered of reading this somewhere, just browsed through:

    C++ Standard Library - A Tutorial and Reference - By Nicolai Josutils

    This finds a mention in:

    5.4.1 Ranges
    The caller must ensure that the first and second arguments define a valid range. This is the case if the end of the range is reachable from the beginning by iterating through the elements. This means, it is up to the programmer to ensure that both iterators belong to the same container and that the beginning is not behind the end. If this is not the case, the behavior is undefined and endless loops or forbidden memory access may result.

提交回复
热议问题