5

Visual Studio 2010 ProWindows 7 64bit机器上使用,我想count(从<algorithm>标题)在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); 
}

上面程序的输出是正确的:

4

但是,我想将值分配给变量并使用int导致编译器警告精度损失的结果。由于valarray没有迭代器,我无法弄清楚如何使用iterartor::difference_type.

这有可能吗?

4

1 回答 1

3

的正确类型Num是:

typename iterator_traits<bool*>::difference_type
    Num=count(&v[0],&v[10],true);

这样做的原因是,count总是返回:

typename iterator_traits<InputIt>::difference_type

InputIt是一个指向布尔的指针:

&v[0];   // is of type bool*
&v[10];  // is of type bool*

对我来说iterator_traits<bool*>::difference_type,评估为long所以你也可以简单地使用:

long Num=count(&v[0],&v[10],true);

但是我不得不承认我没有Visual Studio 2010 Pro明确地测试它。

于 2015-11-08T12:29:26.720 回答