Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the return type of the STL algorithm "count", on a valarray

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?

like image 287
Benny K Avatar asked Oct 19 '22 22:10

Benny K


1 Answers

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.

like image 143
oo_miguel Avatar answered Nov 15 '22 05:11

oo_miguel