Is it possible to peek next element in a container which the iterator currently points to without changing the iterator?
For example in std::set,
int myArray[]= {1,2,3,4}; set <int> mySet(myArray, myArray+4); set <int>::iterator iter = mySet.begin(); //peek the next element in set without changing iterator. mySet.erase(iter); //erase the element if next element is n+1
You can't access set elements by index. You have to access the elements using an iterator. set<int> myset; myset. insert(100); int setint = *myset.
The begin() function of a container returns an iterator that points to the first item in the container. The end() function of a container returns an iterator to the imaginary item one position past the last item in the container. end() marks an invalid position; it must never be dereferenced.
An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent. Iterators act as a bridge that connects algorithms to STL containers and allows the modifications of the data present inside the container.
C++0x adds a handy utility function, std::next
, that copies an iterator, advances it, and returns the advanced iterator. You can easily write your own std::next
implementation:
#include <iterator> template <typename ForwardIt> ForwardIt next(ForwardIt it, typename std::iterator_traits<ForwardIt>::difference_type n = 1) { std::advance(it, n); return it; }
You can use this in your example like so:
if (iter != mySet.end() && next(iter) != mySet.end() && *next(iter) == *iter + 1) mySet.erase(iter);
Not with iterators in general. An iterator isn't guaranteed to be able to operate non-destructively. The classic example is an Input Iterator that actually represents an underlying input stream.
There's something that works for this kind of iterator, though. A Forward Iterator doesn't invalidate previous copies of itself by the act of moving forward through the collection. Most iterators (including those for STL collections) are at least Forward Iterators, if not a more functional version- only Input Iterators or Output Iterators are more restricted. So you can simply make a copy of your iterator, increment the copy and check that, then go back to your original iterator.
So your peek code:
set <int>::iterator dupe = iter; ++dupe; // (do stuff with dupe)
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