简体   繁体   中英

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, ie, std::distance(static_cast<Iter>(Input.begin()),itTarget) everything works fine.

I wonder why is that?

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

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

A second way of doing it: Every iterator is convertible into a 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 have to pack things into the function call you could use some cast 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 a const_iterator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM