You rarely need to use an iterator to directly define it. In particular, iteration through a collection should usually be performed using a general algorithm. If it is already defined there that can carry out this work, it is best to use it. If not, it is better to write your own algorithm as an algorithm. In this case, the iterator type becomes a template parameter with any name that you prefer (as a rule, something belongs, at least, to the iterator category):
template <class InputIterator> void my_algorithm(InputIterator start, InputIterator stop) { for (InputIterator p = start; p != stop; ++p) do_something_with(*p); }
Since they were mentioned, I will point out that IMO, typedef
and C ++ 11 new auto
(at least IMO) are rarely a good answer to this situation. Yes, they can eliminate (or at least reduce) verbosity when defining an object like an iterator, but in this case it basically just considers the symptom, not the disease.
As an aside, I would also like to note that:
- Pointer vector is usually an error.
- Dynamic distribution of the vector is an even more likely error.
At least right away, it looks like you're probably used to something like Java, where you always need to use new
to create the object. In C ++, this is relatively unusual - most of the time you just want to define a local object, so creation and destruction will be processed automatically.
source share