2013-06-04 92 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);這會導致嘗試輸出迭代器的錯誤。再次感謝。 –