STL算法"count"的return类型是什么,在valarray上
What is the return type of the STL algorithm "count", on a valarray
我在 Windows 7 64bit
机器上使用 Visual Studio 2010 Pro
,我想在 count
(来自 <algorithm>
header) 18=]:
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
总是 returns:
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
下明确地测试它。
我在 Windows 7 64bit
机器上使用 Visual Studio 2010 Pro
,我想在 count
(来自 <algorithm>
header) 18=]:
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
总是 returns:
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
下明确地测试它。