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?
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 .
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With