繁体   English   中英

从泛型函数返回迭代器

[英]Returning an iterator from a generic function

我是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;
}

我想修改此函数,以便代替返回布尔值,而将迭代器返回到第一个匹配项。 我将如何去做呢? 如果有人可以向正确的方向推动我,那将真的很有帮助。

我真的不知道如何在不给您答案的情况下将您推向正确的方向,因为它是如此简单。

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所做的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM