Can I do normal computations with iterators, i.e. just increment it by adding a number?
As an example, if I want to remove the element vec[3]
, can I just do this:
std::vector<int> vec; for(int i = 0; i < 5; ++i){ vec.push_back(i); } vec.erase(vec.begin() + 3); // removes vec[3] element
It works for me (g++), but I'm not sure if it is guaranteed to work.
If iter is an InputIterator, you can use: ++iter and iter++ to increment it, i.e., advance the pointer to the next element.
Obviously if the iterator is advanced past the last element inside the loop the comparison in the for-loop statement will evaluate to false and the loop will happily continue into undefined behaviour.
A pointer can point to elements in an array and can iterate through them using the increment operator (++). But, all iterators do not have similar functionality as that of pointers.
Operator= -- Assign the iterator to a new position (typically the start or end of the container's elements). To assign the value of the element the iterator is pointing at, dereference the iterator first, then use the assign operator.
It works if the iterator is a random access iterator, which vector's iterators are (see reference). The STL function std::advance
can be used to advance a generic iterator, but since it doesn't return the iterator, I tend use + if available because it looks cleaner.
C++11 note
Now there is std::next
and std::prev
, which do return the iterator, so if you are working in template land you can use them to advance a generic iterator and still have clean code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With