Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL iterators std::distance() error

I'm having such two typedefs:

typedef std::vector<int> Container;
typedef std::vector<int>::const_iterator Iter;

In the problem that I consider, I perform some operations on Container Input, and after that I would like to compute std::distance(Input.begin(),itTarget), where itTarget is of the Iter type. But I'm getting this compiler error that no instance of function template "std::distance" matches the argument list, and only after casting, i.e., std::distance(static_cast<Iter>(Input.begin()),itTarget) everything works fine.

I wonder why is that?

like image 926
Simon Righley Avatar asked Jun 25 '13 09:06

Simon Righley


People also ask

How do I find the distance between two iterators in C++?

std::distance in C++ If we have two iterators and we want to find the total no. of elements between the two iterators, then that is facilitated by std::distance(), defined inside the header file .

Is distance a keyword in C++?

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.

What is std :: distance?

The std::distance() is an in-built function provided in the Standard Library (STL). The std::distance() method is used to find the distance between two iterators. It takes two iterators as arguments and returns an integer. The returned integer can be both positive and negative based on the order of iterators passed.

Can we subtract 2 iterators in C++?

std::vector<T>::iterator satisfies the RandomAccessIterator concept, which means that it has an operator- that allows you to subtract two iterators and obtain a std::vector<T>::iterator::difference_type that indicates the distance between the two iterators.


1 Answers

std::distance is a template function, it can't accept different parameters. You need to use:

std::distance(Input.cbegin(),itTarget);
                    ^^

see std::vector::cbegin link

like image 158
billz Avatar answered Sep 28 '22 19:09

billz