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