2013-06-04 91 views
0

我是C++的新手,我不确定如何执行此操作。我正在尝试学习模板。从泛型函数返回迭代器

这是我现在的代码。它发送一个容器(未指定它将接收的类型),并在迭代器位于容器中时返回true。如果没有出现,则为假。

#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; 
} 

我想,这样的而不是返回一个布尔值,它返回一个迭代的第一场比赛,以修改此功能。我会如何去做这件事?如果有人能把我推向正确的方向,那将会非常有帮助。

+0

可以使用[std :: find](http://en.cppreference.com/w/cpp/algorithm/find)代替? – billz

+1

先自己刺一下,然后如果你卡住了,发布你已经尝试过的,我们可以提供帮助。 – bcr

回答

3

我真的不知道如何在没有给你答案的情况下将你推向正确的方向,因为它非常简单。

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

+0

谢谢!我不是个聪明人。我早些时候,但使用std :: cout << function(first,last,11);这会导致尝试输出迭代器的错误。再次感谢。 –