[英]Declare a template function which receives two generic iterator as parameters
I need to create a function which receives the iterator from the begin and the end of one container. 我需要创建一个函数,从一个容器的开头和结尾接收迭代器。 Then it should show the content in the console.
然后它应该在控制台中显示内容。
My problem is that i dont know how to declare the iterator so that it can work with any type of container 我的问题是我不知道如何声明迭代器,以便它可以使用任何类型的容器
This is what I did: 这就是我做的:
template <class T>
void print(typename iterator<T> &beg, typename iterator<T> &end) {
while (beg != end) {
cout << *beg << endl;
beg++;
}
}
The std::iterator
class is really just a convenience; std::iterator
类实际上只是一个方便; there's nothing in the standard that requires all iterators to inherit from it. 标准中没有任何内容要求所有迭代器都从它继承。 Additionally,
std::iterator
doesn't have virtual methods, so it's not nearly the same thing as taking an Iterator<T>
in, say, Java, where invoking the next()
method would call the appropriate next()
. 另外,
std::iterator
没有虚方法,所以它与在Java中使用Iterator<T>
几乎不一样,其中调用next()
方法会调用相应的 next()
。 You want to take a general type T
, not just an std::iterator
, so that the compiler will resolve to the correct overloads of operator++
and operator*
at compile-time. 您希望采用通用类型
T
,而不仅仅是std::iterator
,以便编译器在编译时解析为operator++
和operator*
的正确重载。
template <typename T>
void print(T iter, const T& end) {
// Taking the first argument by value ensures that
// we don't modify the caller's variables
while (iter != end) {
cout << *iter << endl;
++iter;
}
}
This will work for any forward iterators, which is what you're dealing with 99% of the time. 这适用于任何前向迭代器,这是你在99%的时间处理的。
I need to create a function which receives the iterator from the begin and the end of one container.
我需要创建一个函数,从一个容器的开头和结尾接收迭代器。
Look how standard functions do it, for example std::find
: 看看标准函数是如何做到的,例如
std::find
:
template< class InputIt, class T >
InputIt find( InputIt first, InputIt last, const T& value );
Observations: 观察:
InputIt
does not need to inherit from the (now obsolete) std::iterator
class or any other class. InputIt
不需要从(现在过时的) std::iterator
类或任何其他类继承。 Among other advantages, this allows the function to be used with an array. Just do it exactly like that in your own code and you'll be fine: 只是在您自己的代码中完全按照这样做,你会没事的:
#include <iostream>
#include <vector>
template <class Iterator> // not T
void print(Iterator beg, Iterator end) {
while (beg != end) {
std::cout << *beg << '\n';
beg++;
}
}
int main() {
std::vector<int> const vec = { 1, 2, 3 };
int const array[] = { 1, 2, 3 };
using std::begin;
using std::end;
print(begin(vec), end(vec));
print(begin(array), end(array));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.