An iterator acts like a pointer to an element inside a container (e.g, maps, vector, list). You can use iterators to navigate through the items, read them, and modify them.
Types of Iterators:
Input Iterators: Can read from a position
Output Iterstors: Can write to a position
Forward Iterators: Can read, write, and move forward.
Bidirectional Iterators: Can move in both directions - forward and backward.
Random Access Iterators: Can jump directly to any position.
Using Iterators in C++:
Containers provide begin()
and end()
functions that return iterators pointing to the start of the container and one-past-the-end, respectively.
std::vector<int> vec = {1, 2, 3, 4, 5};
for(std::vector<int>vec::iterator it = vec.begin(); it != vec.end(); ++it){
std::cout<< *it << " "; //Dereferencing the iterator to get the value
}
In modern C++, you can use auto for type inference. The compiler looks at what vec.begin()
returns and then automatically sets the type of it
accordingly.
for(auto it = vec.begin(); it != vec.end(); ++it){
std::cout<< *it << " ";
}
Differences:
Verbosity: The first approach is more verbose because you have to specify the iterator type. The second approach, using
auto
, is more concise.Flexibility: With
auto
, if you change the container type (say fromstd::vector<int>
tostd::list<int>
), the loop would still work without needing to modify the iterator type in the declaration. This makes the code more adaptable to changes.
Which is Preferred?
The use of auto
for iterator declaration has become more popular and is generally recommended in modern C++ (C++11 and later) for a few reasons:
Readability: It reduces the verbosity of the code and makes it cleaner.
Less Prone to Errors: Since the compiler deduces the type, there's less room for mismatch errors.
Adaptability: As mentioned, it makes the code more resilient to changes in the container type.
In conclusion, while both methods are valid, using
auto
is generally preferred in modern C++ programming due to its simplicity, readability, and adaptability.