In the standard library another "pattern" exists and it's the iterator pattern. Basically every container type implements begin
and end
which returns, respectively, the iterator to the first element and the past-the-end element (which is always guaranteed to exists).
This works for every container type, from std::vector
to std::array
including C-style arrays with std::begin
and std::end
. If you want to loop in a generic container you can do, for example:
template<typename Container>
void cicle(Container const& c) {
for (auto const& i : c) {
// …
}
}
or, to better visualize the pattern:
template<typename Container>
void cicle(Container const& c) {
for (auto it = std::begin(c); it != std::end(c); ++it) {
// …
}
}