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

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

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

template
Function for_each(InputIterator first         


        
5条回答
  •  没有蜡笔的小新
    2021-01-17 19:47

    This is explained by section 24.1 of the standard, "Iterator Requirements":

    An iterator j is called reachable from an iterator i if and only if there is a finite sequence of applications of the expression ++i that makes i == j. If j is reachable from i, they refer to the same container.

    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.

    So v.begin() + 3 is reachable from v.begin(), but not the reverse. So [v.begin()+3, v.begin()) is not a valid range, and your call to for_each is undefined.

提交回复
热议问题