[英]STL iterators std::distance() error
I'm having such two typedefs: 我有两个typedef:
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. 在我考虑的问题中,我对
Container Input
执行了一些操作,之后我想计算std::distance(Input.begin(),itTarget)
,其中itTarget
属于Iter
类型。 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. 但是我得到这个编译器错误,
no instance of function template "std::distance" matches the argument list
,并且只有在转换之后,即std::distance(static_cast<Iter>(Input.begin()),itTarget)
一切工作正常。
I wonder why is that? 我想知道为什么会这样?
std::distance is a template function, it can't accept different parameters. std :: distance是一个模板函数,它不能接受不同的参数。 You need to use:
你需要使用:
std::distance(Input.cbegin(),itTarget);
^^
see std::vector::cbegin link 看到std :: vector :: cbegin链接
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. Input.begin()
返回一个iterator
而不是一个const_iterator
,你的第二个参数是一个const_iterator
,所以这两个参数基本上是不同的类型。 You can use cbegin()
if you have access to C++11 Features. 如果您有权访问C ++ 11功能,则可以使用
cbegin()
。
A second way of doing it: Every iterator is convertible into a const_iterator by assignment 第二种方法:每个迭代器都可以通过赋值转换为const_iterator
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. 如果Input是const,则编译器被强制使用begin()的const-version,它返回一个const_iterator。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.