在 valarray 上 "count" 的 STL 算法的返回类型是什么

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

本文关键字:算法 返回类型 是什么 STL count valarray      更新时间:2023-10-16

我在Windows 7 64bit机器上使用Visual Studio 2010 Pro,我想在valarray:上使用count(来自<algorithm>标头)

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

这有可能吗?

Num的正确类型为:

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

原因是count总是返回:

typename iterator_traits<InputIt>::difference_type

你的InputIt是指向bool:的指针

&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下测试它。