gpt4 book ai didi

c++ - 从泛型函数返回迭代器

转载 作者:行者123 更新时间:2023-11-28 00:44:38 24 4
gpt4 key购买 nike

我是 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;
}

我想修改此函数,使其不返回 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 所做的。

关于c++ - 从泛型函数返回迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16908063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com