[英]Conversion error when returning an Iterator
我正在尝试“查找”功能。 我似乎无法返回迭代器。
template<typename T>
typename T::iterator do_find(const T &v, int f)
{
return find(v.begin(), v.end(), f);
}
这是我的主要内容:
int main()
{
std::vector<int> v = {1, 2, 3, 3, 4, 6};
std::vector<int>::iterator it;
it = do_find(v, 3);
return 0;
}
编译时出现以下错误:
error: impossible de convertir
« std::find<__gnu_cxx::__normal_iterator<const int*, std::vector<int> >, int>((& v)->std::vector<int>::begin(), (& v)->std::vector<int>::end(), f) » de « __gnu_cxx::__normal_iterator<const int*, std::vector<int> > » vers « std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >} »
v
声明为const
,然后对于std::vector
, v.begin()
和v.end()
返回std::vector::const_iterator
,那么find
的返回类型也将为std::vector::const_iterator
; 它不能隐式转换为std::vector::iterator
。
您可以更改返回类型,例如
template<typename T>
typename T::const_iterator do_find(const T &v, int f)
{
return find(v.begin(), v.end(), f);
}
要不就
template<typename T>
auto do_find(const T &v, int f)
{
return find(v.begin(), v.end(), f);
}
然后
auto it = do_find(v, 3);
如果要通过返回的迭代器修改元素,则应将参数v
声明为非常量。
template<typename T>
auto do_find(T &v, int f)
{
return find(v.begin(), v.end(), f);
}
需要注意的是与auto
,上述do_find
将返回iterator
,如果你传递一个非const vector
,并返回const_iterator
如果你通过一个const vector
。
v
是const
; 表示std::find
将返回T::const_iterator
。 您正在尝试返回T::iterator
; 并且编译器无法从const
转换为非const。
解决方法是返回const_iterator
或使v
非常量。 取决于您要对迭代器执行的操作。
在函数内,该容器被声明为常量容器
template <typename T>
typename T::iterator do_find(const T &v, int f);
^^^^^^^^^^
因此,该容器的成员函数的begin
和end
返回类型类型为typename T::const_iterator
对象,这些对象无法隐式转换为该类型。 typename T::iterator
。
同样也不清楚为什么第二个参数的类型为int
而不是类型名称为typename T::value_type
。
C ++中有一个神奇的词auto
,它可以简化函数声明并使用其返回值。
该功能可以通过以下方式定义
template <typename T>
auto do_find( const T &v, typename T::value_type value ){
return std::find( v.begin(), v.end(), value );
}
这是一个示范节目
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
template <typename T>
auto do_find( const T &v, typename T::value_type value ){
return std::find( v.begin(), v.end(), value );
}
int main()
{
std::vector<int> v = { 1, 2, 3, 3, 4, 6 };
auto it = do_find(v, 3);
if ( it != v.end() )
{
std::cout << *it << " is found at position "
<< std::distance( v.cbegin(), it ) << std::endl;
}
return 0;
}
它的输出是
3 is found at position 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.