I need to create a function which receives the iterator from the begin
and the end of one container.
Look how standard functions do it, for example std::find
:
template< class InputIt, class T >
InputIt find( InputIt first, InputIt last, const T& value );
Observations:
InputIt
does not need to inherit from the (now obsolete) std::iterator
class or any other class. Among other advantages, this allows the function to be used with an array.
- The same iterator type is used for start and end.
- The iterators are passed by value.
- The template parameter does not specify the iterators' value type.
Just do it exactly like that in your own code and you'll be fine:
#include <iostream>
#include <vector>
template <class Iterator> // not T
void print(Iterator beg, Iterator end) {
while (beg != end) {
std::cout << *beg << '\n';
beg++;
}
}
int main() {
std::vector<int> const vec = { 1, 2, 3 };
int const array[] = { 1, 2, 3 };
using std::begin;
using std::end;
print(begin(vec), end(vec));
print(begin(array), end(array));
}