【问题标题】:Return an iterator inside a template返回模板内的迭代器
【发布时间】:2014-02-15 05:57:54
【问题描述】:

我正在尝试实现一个简单的模板函数,此代码无法编译,但我希望它能让您了解我正在尝试做什么:

template<typename T>
typename T::iterator   do_find(const T& container, const int val)
{
   return std::find(container.begin(), container.end(), val);
}

我想返回 find 自己返回的迭代器,但不知道我在模板函数 do_find 中收到的容器类型。我做错了什么?

这里是主要的:

int             main()
{
  std::vector<int>      c;

  c.push_back(42);
  c.push_back(0);
  c.push_back(1);
  c.push_back(-58);
  c.push_back(42);
  c.push_back(777);
  c.push_back(1911);
  c.push_back(9);

  do_find(c, 42);

  return 0;
}

还有编译器错误:

In file included from main.cpp:14:0:
find.hpp: In instantiation of ‘typename T::iterator do_find(const T&, int) [with T = std::vector<int>; typename T::iterator = __gnu_cxx::__normal_iterator<int*, std::vector<int> >]’:
main.cpp:29:16:   required from here
find.hpp:17:59: error: could not convert ‘std::find<__gnu_cxx::__normal_iterator<const int*, std::vector<int> >, int>((& container)->std::vector<_Tp, _Alloc>::begin<int, std::allocator<int> >(), (& container)->std::vector<_Tp, _Alloc>::end<int, std::allocator<int> >(), (* & val))’ from ‘__gnu_cxx::__normal_iterator<const int*, std::vector<int> >’ to ‘std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}’
find.hpp: In function ‘typename T::iterator do_find(const T&, int) [with T = std::vector<int>; typename T::iterator = __gnu_cxx::__normal_iterator<int*, std::vector<int> >]’:
find.hpp:18:1: error: control reaches end of non-void function [-Werror=return-type]
cc1plus: all warnings being treated as errors

【问题讨论】:

    标签: c++ templates vector iterator typename


    【解决方案1】:

    如果您将const T&amp; container 作为此函数的第一个参数,则必须改为返回typename T::const_iterator

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 2010-09-30
      相关资源
      最近更新 更多