I'm using Visual Studio 2010 Pro on a Windows 7 64bit machine and I want to use count (from the <algorithm> header) on a valarray:
int main()
{
valarray<bool> v(false,10);
for (int i(0);i<10;i+=3)
v[i]=true;
cout << count(&v[0],&v[10],true) << endl;
// how to define the return type of count properly?
// some_type Num=count(&v[0],&v[10],true);
}
The output of the program above is correct:
4
However I want to assign the value to a variable and using int results in compiler warnings about loss of precision. Since valarray has no iterators, I can't figure out how to use the iterartor::difference_type.
Is this somehow possible?
The correct type for Num would be:
typename iterator_traits<bool*>::difference_type
Num=count(&v[0],&v[10],true);
The reason for this is, that count always returns:
typename iterator_traits<InputIt>::difference_type
and your InputIt is a pointer to bool:
&v[0]; // is of type bool*
&v[10]; // is of type bool*
For me iterator_traits<bool*>::difference_type evaluates to long so you might also get away with simply using:
long Num=count(&v[0],&v[10],true);
However I have to admit I did not test it under Visual Studio 2010 Pro explicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With