Is it possible to call std :: search_n with a score of 0?

Can std::search_n be called "safe" with count 0? In particular, such a code is as follows:

 #include <algorithm> #include <cstdio> int main(int argc, char *argv[]) { const int test[7] = {1, 2, 3, 4, 5, 6, 7}; const int *const location = std::search_n(test, test + 7, 0, 8); if (location == test) { std::puts("Found it at the beginning!"); } } 

I expect this code to reach the std::puts statement, and most std::search_n descriptions seem to imply that this will happen. However, most of the implementation examples that I find will not. What does the standard say?

+7
c ++ stl-algorithm
source share
1 answer

The std::search_n specification (Β§25.2.13 [alg.search] / p4-7):

 template<class ForwardIterator, class Size, class T, class BinaryPredicate> ForwardIterator search_n(ForwardIterator first, ForwardIterator last, Size count, const T& value, BinaryPredicate pred); 

4 Required: Type Size must be convertible to an integral type (4.7, 12.3).

5 Effects: Finds a subsequence of equal values ​​in a sequence.

6 Returns: the first iterator i in the range [first,last-count) such that for each non-negative integer n less than count following the appropriate conditions: *(i + n) == value, pred(*(i + n),value) != false . Returns last if no such iterator was found.

7 Complexity: no more than last - first applications corresponding predicate.

If count <= 0 there is no non-negative integer n less than count , therefore the condition "for any non-negative integer * n less than count ..." is always true ** and therefore it should return the first iterator in the range that is equal to first . Note that the specification implies that you are not allowed to pass a negative count if last-count not correct, but nothing in the specification allows count have a null value.

All standard library implementations that I tested (libstd ++, lib ++, MSVC) print a message.


* It used to be "for anyone ...". LWG issue 2150 reworded here to clarify the intended meaning.

** The statement "for each x of S, p" is vacuously true if S is an empty set.

+5
source share

All Articles