gpt4 book ai didi

c++ - 在模板中返回一个迭代器

转载 作者:太空狗 更新时间:2023-10-29 20:13:27 25 4
gpt4 key购买 nike

我正在尝试实现一个简单的模板函数,这段代码无法编译,但我希望它能让您了解我正在尝试做什么:

template<typename T>
typename T::iterator do_find(const T& container, const int val)
{
return std::find(container.begin(), container.end(), val);
}

我想返回 find 自身返回的迭代器,而不知道我在模板函数 do_find 中收到的容器类型。我做错了什么?

主要是:

int             main()
{
std::vector<int> c;

c.push_back(42);
c.push_back(0);
c.push_back(1);
c.push_back(-58);
c.push_back(42);
c.push_back(777);
c.push_back(1911);
c.push_back(9);

do_find(c, 42);

return 0;
}

编译器错误:

In file included from main.cpp:14:0:
find.hpp: In instantiation of ‘typename T::iterator do_find(const T&, int) [with T = std::vector<int>; typename T::iterator = __gnu_cxx::__normal_iterator<int*, std::vector<int> >]’:
main.cpp:29:16: required from here
find.hpp:17:59: error: could not convert ‘std::find<__gnu_cxx::__normal_iterator<const int*, std::vector<int> >, int>((& container)->std::vector<_Tp, _Alloc>::begin<int, std::allocator<int> >(), (& container)->std::vector<_Tp, _Alloc>::end<int, std::allocator<int> >(), (* & val))’ from ‘__gnu_cxx::__normal_iterator<const int*, std::vector<int> >’ to ‘std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}’
find.hpp: In function ‘typename T::iterator do_find(const T&, int) [with T = std::vector<int>; typename T::iterator = __gnu_cxx::__normal_iterator<int*, std::vector<int> >]’:
find.hpp:18:1: error: control reaches end of non-void function [-Werror=return-type]
cc1plus: all warnings being treated as errors

最佳答案

如果您将 const T& container 作为此函数的第一个参数,则必须返回 typename T::const_iterator

关于c++ - 在模板中返回一个迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21329307/

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