Iteration

Good Day!

I'm a little bit confused with C++ STL iterators.

Is there any way to iterate over containers of different type with the elements of the same type?

Say, I've got two containers of double: std::valarray<double> and std::vector<double>. I need to iterate over them with no information about exact type.

1
2
3
4
5
6
7
8
9
void someIterateFunction(<some_iterator_type> iter, <some_iterator_type> stop)
{
    for (;iter != stop; ++iter)
        <do_something_here_with> *iter;
}

void someIterateFunction(std::valarray<double>::iter arr.begin(), std::valarray<double>::iter arr.end());

void someIterateFunction(std::vector<double>::iter vec.begin(), std::vector<double>::iter vec.end());
You could use a function template.

http://www.cplusplus.com/doc/tutorial/functions2/#templates

1
2
3
4
5
6
template <typename Iterator>
void someIterateFunction(Iterator first, Iterator last)
{
    for (; first != last; ++first)
        // do something with *first
}
Catfish666, thanks a lot!
Topic archived. No new replies allowed.