views:

415

answers:

2

I'd like to create two containers that contain iterators to each other. I'd like to do this hopefully without introducing any intermediate/indirect types. Is this possible or do iterator types depending on knowing the size of the container's data type?

Here is some sample code that I'd like to get compiling:

#include <map>
#include <deque>
#include <string>

class mapvalue_t
{
  public:
    std::deque< std::map<std::string,mapvalue_t>::iterator  >::iterator i;
};

typedef std::map<std::string,mapvalue_t> maptype_t;
typedef std::deque< maptype_t::iterator > queuetype_t;

int main(void)
{
  maptype_t m;
  queuetype_t q;
}

Never mind, it compiles now. I had a queue there, rather than my intended deque :)

+2  A: 

This works if you use a deque instead of a queue. Queue is not a container, but a facade so it does not support the ::iterator call.

From cplusplus.com:

queues are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access it elements. Elements are pushed into the "back" of the specific container and popped from its "front".

Alex B
+1  A: 

You should be very careful about storing iterators. Modifying the collection can easily invalidate all iterators. You would be far better storing an id or a (managed) pointer.

DanDan
Indeed. Your stored list of iterators will invalidate every time the map is modified in any way. You should store key values to the mapping.
Kieveli
Not quite true. For map and list, inserting and deleting elements does not invalidate any iterators (except of course for the one being deleted).My question should have a list and not a deque in it, but I don't know if I should bother updating the question yet again.
Cruzton
If we rely on specific implementations. I don't think this is guaranteed by the standard.
DanDan