Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Peeking the next element in STL container

Tags:

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 
like image 592
user963241 Avatar asked Sep 09 '10 04:09

user963241


People also ask

How do you access set elements in STL?

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.

What should begin () and end () do for a container?

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.

What is the use of iterate over container in STL?

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.


2 Answers

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); 
like image 139
James McNellis Avatar answered Sep 23 '22 04:09

James McNellis


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) 
like image 33
Adam Norberg Avatar answered Sep 23 '22 04:09

Adam Norberg