简体   繁体   中英

Returning an iterator from a generic function

I am new to C++ and I am unsure how to do this. 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. False if it does not appear.

#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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