Re: return type of count in std::algorithm
On Feb 13, 7:45 am, "subramanian10...@yahoo.com, India"
<subramanian10...@yahoo.com> wrote:
Consider the following piece of code:
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstddef>
using namespace std;
int main()
{
vector<string> v;
v.push_back("zero");
v.push_back("one");
v.push_back("two");
v.push_back("three");
v.push_back("test string");
v.push_back("another string");
iterator_traits< vector<string>::iterator >::difference_type c ==
count(v.begin(), v.end(), string("test string"));=
cout << c << endl;
int arr[] = { 0, 1, 2, 3, 0, 1, 2 };
ptrdiff_t i = count(arr, arr + (sizeof(arr) / sizeof(arr[0])), 2=
);
cout << i << endl;
return EXIT_SUCCESS;
}
In the above code, I had to use two different types for the return
type of std::count().
Not really.
Instead is there a common return type which I can use ?
The one you used. In the second case, you also could have used:
iterator_traits< int* >::difference_type
instead of ptrdiff_t. In the first case, you could just as
easily have used ptrdiff_t.
In the standard containers, difference_type is defined as being
the difference_type of the allocator used. And difference_type
in the standard default allocator is defined as being a typedef
to ptrdiff_t.
Also the first return type
iterator_traits< vector<string>::iterator >::difference_type
is lengthy. Is there a shorter form ?
ptrdiff_t.
In most code, ptrdiff_t is just fine, and is a lot more readable
than the complicated expression. (For that matter, in most
code, int is just fine. There are a lot of contexts where you
can be trivially sure that the total number of elements in the
sequence will never be more than INT_MAX.)
About the only time I'd use the longer forms is in generic code,
designed to work with any iterator or any container the user
passed in. Something like:
template< typename FwdIter >
typename std::iterator_traits< FwdIter >::difference_type
...
It only makes sense to go to this effort (and add this amount of
obfuscation) if 1) you're in a template, and 2) either the
template is designed to be part of a general library, to be used
in many different applications, some of which aren't even known
yet, or you're application actually does use non-standard
allocators.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34