简体   繁体   English

从泛型函数返回迭代器

[英]Returning an iterator from a generic function

I am new to C++ and I am unsure how to do this. 我是C ++的新手,我不确定如何做到这一点。 I am trying to learn templates. 我正在尝试学习模板。

This is my current code. 这是我当前的代码。 It sends a container (not specified which type it will receive) and returns true if the integer passes alongside the iterators is in the container. 它发送一个容器(未指定它将接收的类型),并且如果整数在容器中与迭代器并排传递,则返回true。 False if it does not appear. 如果未出现,则为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;
}

I would like to modify this function so that instead of returning a bool, it returns an iterator to the first match. 我想修改此函数,以便代替返回布尔值,而将迭代器返回到第一个匹配项。 How would I go about doing this? 我将如何去做呢? It would be really helpful if someone could push me in the right direction. 如果有人可以向正确的方向推动我,那将真的很有帮助。

I don't really know how to push you in the right direction without just giving you the answer, since it is so simple. 我真的不知道如何在不给您答案的情况下将您推向正确的方向,因为它是如此简单。

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
}

By the way, this is exactly what std::find does. 顺便说一句,这正是std::find所做的。

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

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