从泛型函数返回迭代器
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;
}
我想修改这个函数,使它不再返回bool值,而是返回第一个匹配的迭代器。我该怎么做呢?如果有人能指引我正确的方向,那就太好了。
我真的不知道如何在不给你答案的情况下把你推向正确的方向,因为这太简单了。
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
所做的。
相关文章:
- 使用 map<char,strring> 的迭代器返回指针 map<char,strring>*
- 如何从高性能的输入迭代器返回变体?
- 如何为迭代器返回"null"值?
- 将迭代器返回到向量的函数
- 迭代器返回 vector::begin()
- 访问对向量以使用迭代器返回
- 获取迭代器返回的字符串的大小()
- 如何让Lua迭代器返回C结构
- 迭代器返回最后一个元素上的"Junk"
- 指向矢量迭代器返回值的指针
- 使用迭代器返回对字符串的引用
- 如何将指针作为迭代器返回
- 将迭代器返回到多映射中最接近指定时间的时间
- 通过迭代器返回set对象的地址
- 从迭代器返回一个std::list元素的引用
- 为我的向量包装器和迭代器返回'begin'和'end'函数返回什么?
- c++迭代器返回类型
- 从取消引用的迭代器返回 std::map<std::string, int> 时出现巨大的内存泄漏
- 迭代器返回垃圾
- 通过不使用模板的迭代器返回std::list