简体   繁体   中英

Declare a function accepting generic iterator

Given this code, is it possible to change dumpStrings() to be able to iterate over any container of string , like say a list<string> ?

#include <vector>
#include <string>
#include <ostream>
#include <iostream>

using namespace std;

void dumpStrings(vector<string>::iterator it, vector<string>::iterator end)
{
    while (it != end) {
        cout << *it++ << endl;
    }
}

int main()
{
    vector<string> strVector;
    strVector.push_back("Hello");
    strVector.push_back("World");

    dumpStrings(strVector.begin(), strVector.end());
    return 0;
}

Create a template

template<class iterator_type>
void dumpStrings(iterator_type it, iterator_type end)
{
    while (it != end) {
        cout << *(it++) << endl;
    }
}

The template also removes the limit of the container value type to string. Note that you need the parentheses around the it++.

I don't think there's anything as simple as you'd like. Ideally, you could just do something like

void dumpStrings(AbstractIterator<string> beg, AbstractIterator<string> end) { }

but the STL iterators don't seem to have any inheritance hierarchy, irritatingly enough. So it looks like you're stuck with using function templates - that's how it's done in the STL Algorithms Library .

Sorry - I wish there was a better way, too, but this'll have to do. Just remember to declare the full function template in the header file!

Please try this, this would work in all container:

template<class T>
void disp(T &t)
{
    for( auto itr=t.begin();itr!=t.end();itr++)
        cout<<*itr<<endl;
}

.cpp
    vector<int> v(3,77);
    list<string> l(5,"Hello");
    disp(l)
    disp(v);

Note: Don't forget to include< string >,
And auto is available in c++ 11

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM