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;
}
我想,這樣的而不是返回一個布爾值,它返回一個迭代的第一場比賽,以修改此功能。我會如何去做這件事?如果有人能把我推向正確的方向,那將會非常有幫助。
可以使用[std :: find](http://en.cppreference.com/w/cpp/algorithm/find)代替? – billz
先自己刺一下,然後如果你卡住了,發佈你已經嘗試過的,我們可以提供幫助。 – bcr