簡體   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