STL iterators std :: distance () error

I have two typedef types:

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

In the problem under consideration, I perform some operations on Container Input , after which I would like to calculate std::distance(Input.begin(),itTarget) , where itTarget is of type Iter . But I get this compiler error 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?

+6
source share
2 answers

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

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

see std :: vector :: cbegin link

+8
source

Input.begin() returns an iterator instead of a const_iterator , and your second argument is const_iterator , so the two arguments are basically of a different type. You can use cbegin() if you have access to the features of C ++ 11.

The second way to do this: Each iterator is converted to const_iterator by assignment

 std::vector<int> myVector(100); std::vector<int>::iterator it = myVector.begin(); std::vector<int>::const_iterator cit = it; 

If you need to send things to a function call, you can use magic magic:

 std::distance( ((const Container*)&Input)->begin(), itTarget ); 

If Input is const, the compiler is forced to use the const version of begin (), which returns const_iterator.

+5
source

Source: https://habr.com/ru/post/948051/


All Articles