1

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?

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?

4

4 回答 4

3

If you want your function to accept an iterator, then you cannot use the for (auto i: cont) syntax. Indeed, this new range-based for syntax wants the container, not an iterator.

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).

template <class IT>
void f(IT first, IT last) {
    for ( ; first!=last ; ++first)
        cout << first;
}
于 2012-11-19T16:17:48.093 回答
2

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.

于 2012-11-19T16:09:57.873 回答
1

There is a boost::any_iterator somewhere. But the Standard does not provide one.

于 2012-11-19T16:09:52.597 回答
0

If you are looking for a way to return a mostly unspecified iterator type (e.g. because the function signature in a base class can't fix the exact type of the iterator yet), you could have a look at C++: "Iterable<T>" interface

于 2021-04-30T18:22:04.010 回答