Why does std :: count_if return a signed value instead of unsigned?

I just realized that std::count_if returns a std::count_if value .

Why is it designed this way? This does not make sense (in my opinion, the result can only be a natural number, that is, a non-negative integer), since it does not allow you to do something as simple as comparing this result with the size() container without warning or using an explicit conversion types.

I really think the return type should have size_type .

Did I miss something?

+6
source share
1 answer

I think the return type tends to be compatible with std::count , which takes two iterators (thinks of pointers) and returns values ​​between them (which you can consider as the difference of two pointers). The difference of pointers (as used in ptrdiff_t ) should be significant.

Thanks to compatibility with std::count you can easily compare the results of these two functions.

Edit: here there is no restriction related to the range using the signed value, since the value will at least be in the range [0, std::count] , which itself will be in the range [0, end_ptr - start_ptr] . Since end_ptr - start_ptr is entered as ptrdiff_t or similar, it is signed.

+2
source

Source: https://habr.com/ru/post/983579/


All Articles