c++ - 在模板中返回一个迭代器

标签 c++ templates vector iterator typename

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

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

最佳答案

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

关于c++ - 在模板中返回一个迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21329307/

相关文章:

c++ - 模板成员函数上的外线 sfinae 是否可能?

java - 更改 Java Struts 应用程序中的默认文件结构

c++ - 如何为std::vector调整大小以分配默认值

c++ - C++ 中 std::vector 的基本问题

C++,二维 vector 分割错误

c++ - 如何在 ACE 中获取本地时间而不是 UTC 时间?

c++ - 继承自非专用模板(共享库)

c++ - C++ 中的二进制 .dat 文件问题

c++ - 在没有游戏引擎/渲染窗口的情况下将游戏服务器线程循环限制为 30FPS

c++ - 类模板与成员模板