Why do std::count(_if) return iterator::difference_type instead of size_t? [duplicate]
-
03-07-2021 - |
Question
Possible Duplicate:
Why does the C++ standard algorithm “count” return a ptrdiff_t instead of size_t?
There is algorithm std::count
/std::count_if
in standard C++.
template<class InputIterator, class T>
typename iterator_traits<InputIterator>::difference_type
count(InputIterator first, InputIterator last, const T& value);
template<class InputIterator, class Predicate>
typename iterator_traits<InputIterator>::difference_type
count_if(InputIterator first, InputIterator last, Predicate pred);
Effects: Returns the number of iterators i in the range [first,last) for which the following corresponding conditions hold: *i == value, pred(*i) != false.
difference_type
is iterator's difference_type
, which can be negative, but count
can return only value >= 0. Why difference_type
and not size_t
for example?
Solution
In theory you may have a tremendous sequence whose number of elements can only be represented with 128 bits. Assuming the implementation supports a corresponding integer type, it is quite likely that size_t
use a 64 bit type. However, the iterator for this huge sequence could use a 128 bit integer. Note, that the sequence isn't necessary represented in the memory of any individual computer. It may be split across multiple huge databases.
You might also have a relatively small computer supporting only a 32 bit type with reasonable performance. For full standard conformance it might have to support a 64 bit type but it can be desirable to rather support faster computations using a representation natively supported by the platform. That is, size_t
may not be the optimal choice. When creating iterators you generally know what size needs to be supported.