Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through an unknown type?

I've got this function:

set<int> Search(const _Type & hayHeap) const {
        set<int>myset;
        for (vector<typename>::const_iterator i = needle.begin(); i != needle.end(); ++i) {
            cout << (*i) << " ";
        }
        return myset;
    };

and needle is defined like this:vector<string> needle;

Now I need to create another iterator, that will iterate through hayHeap. But the problem is, that I don't know, what type will it be. It could be a single string or vector of <int>/<string> as well. So when there is a string, it iterates only once, if there is some vector it iterates (myVector.count()-1)-times. How to make this type independent iterator?

like image 532
Martin Dvoracek Avatar asked Nov 29 '25 12:11

Martin Dvoracek


1 Answers

In C++03:

template <typename C>
set<int> Search(const C& hayHeap) const {
    set<int>myset;
    for (typename C::const_iterator i = needle.begin(); i != needle.end(); ++i) {
        cout << (*i) << " ";
    }
    return myset;
};

In C++11:

template <typename C>
set<int> Search(const C& hayHeap) const {
    set<int>myset;
    for (auto& i : needle) {
        cout << i << " ";
    }
    return myset;
};

Depending on your actual needs, you'd replace int by typename C::value_type

like image 61
sehe Avatar answered Dec 01 '25 00:12

sehe