Finding length of range in C++

Viewed 1976

I have defied a range and I need to find the number of elements in it. My current code is

size_t c = 0;
for(auto elem : range){
     c++;
}
return c;

However, the compiler is whining about the unused variable elem and I can't get rid of it. I though of using something like

std::count_if(range.begin(), range.end(), [](type elem){return ture;});

But I feel it is an overkill and it does not seem right.

I am wondering if there is a nicer systematic way of achieving this without defining an extra variable?

3 Answers

If (for some reason) your range doesn't have a size() member function, you can use std::distance. This should always work since a range is required to have a begin and end iterator.

std::distance(cbegin(range), cend(range));

You can use std::distance like

std::distance(range.begin(), range.end());

Returns the number of hops from first to last.

And note the complexity:

Complexity

Linear.

However, if InputIt additionally meets the requirements of LegacyRandomAccessIterator, complexity is constant.

In C++ all the containers implement size method of a constant complexity so if by range you consider a container then there is no need for reinventing the wheel.

However, you can also use std::distance if you want to determine the number of elements from a certain range like:

std::vector<int> v{ 3, 1, 4 };
std::cout << std::distance(v.begin(), v.end() << std::endl; // 3

If you take a look at the possible implementation of std::distance, it is something like

while (first != last) {
    ++first;
    ++n;
}

where first and the last are start and end point of you range, and n is a simple counter.

Related