S
subramanian100in
Below is my understanding about count algorithms.
Return type of count and count_if algorithms is
iterator_traits<InputIterator>::difference_type.
If the container contains more than 'difference_type' elements
satisfying the condition, then count and count_if algorithm cannot
return a value greater than 'difference_type'.
As an example, suppose maximum value of 'difference_type' is INT_MAX.
Then the corresponding maximum value of 'size_type' is UINT_MAX. Now
consider the declaration
vector<char> v;
where 'v' contains UINT_MAX elements each of which is 'a'.
Now if I do
count(v.begin(), v.end(), 'a')
then the actual count would be UINT_MAX but it cannot be represented
in 'difference_type' which is the return type of count algorithm.
So' won't we get erroneous results from count algorithms ?
I understand that difference_type is same as ptrdiff_t for
pointers(belonging to the same array) and size_type if same as size_t.
This means that the count algorithms can never return values from
ptrdiff_t + 1 upto size_t.
Is this understanding correct ?
If what I have mentioned is really a problem with count algorithms,
how should I count the elements in a container satisfying the
condition for large number of elements(ie greater than
difference_type) ?
Kindly clarify.
Thanks
V.Subramanian
Return type of count and count_if algorithms is
iterator_traits<InputIterator>::difference_type.
If the container contains more than 'difference_type' elements
satisfying the condition, then count and count_if algorithm cannot
return a value greater than 'difference_type'.
As an example, suppose maximum value of 'difference_type' is INT_MAX.
Then the corresponding maximum value of 'size_type' is UINT_MAX. Now
consider the declaration
vector<char> v;
where 'v' contains UINT_MAX elements each of which is 'a'.
Now if I do
count(v.begin(), v.end(), 'a')
then the actual count would be UINT_MAX but it cannot be represented
in 'difference_type' which is the return type of count algorithm.
So' won't we get erroneous results from count algorithms ?
I understand that difference_type is same as ptrdiff_t for
pointers(belonging to the same array) and size_type if same as size_t.
This means that the count algorithms can never return values from
ptrdiff_t + 1 upto size_t.
Is this understanding correct ?
If what I have mentioned is really a problem with count algorithms,
how should I count the elements in a container satisfying the
condition for large number of elements(ie greater than
difference_type) ?
Kindly clarify.
Thanks
V.Subramanian