从泛型函数返回迭代器

Returning an iterator from a generic function

本文关键字:迭代器 返回 函数 泛型      更新时间:2023-10-16

我是c++的新手,我不确定如何做到这一点。我正在尝试学习模板。

这是我当前的代码。它发送一个容器(未指定它将接收哪种类型),如果整数与迭代器一起在容器中传递,则返回true。如果没有出现,则为False。

#include <iostream>
#include <vector>
#include <list>
template <typename Iter>
bool function(Iter first, Iter last, const int x)
{
  for (auto it = first; it!=last; ++it)
  {
    if (*it == x)
    {
      return true;
    }
  }
return false;
}
int main()
{
  std::vector<int> vec = {1,2,5,10,11}; 
  std::list<int> lis = {1,1,5,9,55};
  auto first = vec.begin(), last = vec.end();
  auto first2 = lis.begin(), last2 = lis.end();
  std::cout<<function(first, last, 11);
  std::cout<<function(first, last, 9)<<std::endl;
  std::cout<<function(first2, last2, 6);
  std::cout<<function(first2, last2, 55)<<std::endl;
return 0;
}

我想修改这个函数,使它不再返回bool值,而是返回第一个匹配的迭代器。我该怎么做呢?如果有人能指引我正确的方向,那就太好了。

我真的不知道如何在不给你答案的情况下把你推向正确的方向,因为这太简单了。

template <typename Iter>
Iter // change 1
function(Iter first, Iter last, const int x)
{
  for (auto it = first; it!=last; ++it)
  {
    if (*it == x)
    {
      return it; // change 2
    }
  }
  return last; // change 3
}

顺便说一下,这正是std::find所做的。