Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many elements are there between two iterators

Tags:

c++

stl

What's the best way to count all elements in an iterator?

I want code equivalent to this

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());

What's the best way to do that?

I can use boost::lambda::constant(true), but maybe there's something clearer.

like image 570
Elazar Leibovich Avatar asked Oct 09 '11 10:10

Elazar Leibovich


People also ask

How do you find the number of elements between two iterators?

The distance() function in C++ helps find the distance between two iterators. In other words, we can use this function to calculate the number of elements present between the two iterators. This function is available in the <iterator> header file.

Can we subtract 2 iterators in C++?

If two unrelated iterators (including pointers) are subtracted, the operation results in undefined behavior [ISO/IEC 14882-2014]. Do not subtract two iterators (including pointers) unless both point into the same container or one past the end of the same container.

How do you compare two iterators?

we can use == and != to compare to valid iterators into any of the library containers. The section also tells us that iterators for string and vector support relational operators (aka iterator arithmetic) which include >, >=, <, <=.

How do you find the distance between two elements in a set C++?

Syntax: std::distance(InputIterator first, InputIterator last) Here, first and last are input iterators between which we have to calculate distance. Returns: The number of elements between first and last.


1 Answers

If you want to count all elements in a range. then you can use std::distance, from the <iterator> header, like so:

int count = std::distance(begin(c), end(c));

It should be enough.

The online doc says about std::distance:

Calculates the number of elements between first and last.

like image 68
Nawaz Avatar answered Sep 28 '22 10:09

Nawaz