所有容器都具有.size()函数吗? [英] Do all containers have a .size() function?
问题描述
对于家庭作业,我必须创建一个可以在任何容器上执行的模板化标准差函数.这就是我所拥有的:
For a homework assignment I have to create a templatized standard deviation function that can be performed on any container. Here's what I have:
template <typename Container>
double findMean(Container c, int count){
double sum = 0;
for (auto&& e : c){
sum += e;
}
sum /= count;
return sum;
}
template <typename Container>
double findStDev(Container c){
double mean = findMean(c, c.size());
std::cout << mean << std::endl;
for (auto&& e : c){
e -= mean;
e *= e;
}
mean = sqrt(findMean(c, c.size()));
return mean;
}
第一次找到均值要除以容器的全部大小(n),但是第二次找到标准差时,我需要除以size-1(n-1)).
The first time I find the mean I want to divide by the full size of the container (n), but when I find it the second time for the standard deviation, I need to divide by size-1 (n-1).
.size()函数是否可用于所有c ++容器?
Is the .size() function available for all c++ containers?
推荐答案
几乎.根据表96-N3797中的容器要求,标准库中的所有容器都必须提供成员函数 size
.它应具有恒定的执行时间,并返回容器 a
的 distance(a.begin(),a.end())
值.
Almost. By table 96 - container requirements in N3797, all containers in the standard library must provide a member function size
. It shall have constant execution time and return the value of distance(a.begin(),a.end())
for a container a
.
但是,稍后将提到一个(只有一个)例外:
However, there is one (and only one) exception mentioned later on:
forward_list满足容器的所有要求(表96),但size()成员除外功能未提供.
A forward_list satisfies all of the requirements of a container (Table 96), except that the size() member function is not provided.
(N3797 23.3.4.1第2条)
(N3797 23.3.4.1 Clause 2)
这意味着 std :: forward_list
实际上是一个标准容器,没有 没有成员函数 size
.
That means that std::forward_list
is indeed a standard container that does not have a member function size
.
这篇关于所有容器都具有.size()函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!