Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/158.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 两个迭代器之间有多少个元素_C++_Stl - Fatal编程技术网

C++ 两个迭代器之间有多少个元素

C++ 两个迭代器之间有多少个元素,c++,stl,C++,Stl,计算迭代器中所有元素的最佳方法是什么 我想要与此等效的代码 template<typename T,typename S,S val> struct ConstantFunctor : unary_function<T,S> {S operator()(const T&) const {return val;}}; template<typename T> struct TrueFunctor : ConstantFunctor<T,bool,t

计算迭代器中所有元素的最佳方法是什么

我想要与此等效的代码

template<typename T,typename S,S val>
struct ConstantFunctor : unary_function<T,S>
{S operator()(const T&) const {return val;}};
template<typename T>
struct TrueFunctor : ConstantFunctor<T,bool,true>{};
...
count_if(c.begin(),c.end(),TrueFunctor());
模板
结构恒常函数:一元函数
{S operator()(const T&)const{return val;}};
模板
结构真函子:恒常函数{};
...
如果(c.begin(),c.end(),TrueFunctor()),则计数;
最好的方法是什么


我可以使用
boost::lambda::constant(true)
,但如果要计算某个范围内的所有元素,可能还有更清楚的方法。

。然后您可以从标题中使用,如下所示:

int count = std::distance(begin(c), end(c));
应该足够了

上面说的是关于std::distance:

计算第一个和最后一个之间的图元数


为什么不使用
std::distance
?@Vinzenz这就是我要找的。。。他对我来说,计算两个迭代器之间的所有元素听起来像是获取元素的值并将它们相加,这就是
累加
。如果您想知道范围内有多少元素,我认为如果您更改问题标题会有所帮助。@davidhigh:这是2015年,C++14已经发布,所以C++的默认含义应该是C++14,除非另外提到版本。