[英]C++11 iterator interface
Is it possible to create in C++11
a function, which will accept any iterator
as input argument in particular stl containers like vector
or list
?是否可以在
C++11
创建一个函数,该函数将接受任何iterator
作为输入参数,特别是像vector
或list
这样的 stl 容器?
I want to write something like我想写一些类似的东西
void f(iterator<int> i){
for (auto el : i)
cout << el;
}
int main(){
vector<int> v;
list<int> l;
...
f(v);
f(l);
}
Is it possible?是否有可能?
If you want your function to accept an iterator, then you cannot use the for (auto i: cont)
syntax.如果您希望函数接受迭代器,则不能使用
for (auto i: cont)
语法。 Indeed, this new range-based for syntax wants the container, not an iterator.事实上,这种新的基于范围的 for 语法需要容器,而不是迭代器。
Then, your can easily make your function a function template, passing the container.然后,您可以轻松地使您的函数成为函数模板,传递容器。
template <class CONT>
void f(CONT &cont){
for (auto el : cont)
cout << el;
}
If you want to keep passing iterators, then you'll have to go the template way too, but you have to pass two iterators as arguments.如果您想继续传递迭代器,那么您也必须采用模板方式,但您必须将两个迭代器作为参数传递。 One for the first, another for the last (just like the
algorithm
does).一个用于第一个,另一个用于最后一个(就像
algorithm
一样)。
template <class IT>
void f(IT first, IT last) {
for ( ; first!=last ; ++first)
cout << first;
}
No. You can write a function template that accepts any iterator as parameter, but not a function.不可以。您可以编写接受任何迭代器作为参数的函数模板,但不能接受函数。
If you had a class that did type erasure for iterators then you could take that as a parameter.如果您有一个为迭代器执行类型擦除的类,那么您可以将其作为参数。 Here's an article and code for iterator type erasure .
这是迭代器类型擦除的文章和代码。
There is a boost::any_iterator somewhere.某处有一个 boost::any_iterator 。 But the Standard does not provide one.
但是标准没有提供。
如果您正在寻找一种返回大多数未指定迭代器类型的方法(例如,因为基类中的函数签名还不能修复迭代器的确切类型),您可以看看C++:“Iterable<T> “ 界面
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.