Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::count_if return signed value instead of unsigned? [duplicate]

Just realized that std::count_if returns a signed value.

Why is it designed this way? It makes no sense (the result can only be a natural number, i. e. non-negative integer) in my opinion, as it doesn't allow doing something as simple as comparing this result to the container's size() without either getting a warning or using explicit type conversion.

I really think the return type should have size_type.

Am I missing something?

like image 226
Violet Giraffe Avatar asked Mar 10 '15 08:03

Violet Giraffe


1 Answers

I think the return type aims to be compatible to std::count which takes two iterators (think of pointers) and return the values in between (which you can think of as a difference of two pointers). A pointer difference (as used in ptrdiff_t) has to be a signed value.

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

Edit: There is no range related drawback using a signed value here, 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]. Because end_ptr - start_ptr is typed as ptrdiff_t or similar, it's signed.

like image 104
urzeit Avatar answered Oct 23 '22 22:10

urzeit