Reputation: 1802
I have a container class which is essentially (showing relevant parts only)
class Foo {
typedef std::map<int, std::vector<int>> data_t;
data_t data;
struct iterator {
data_t::iterator major_it;
data_t::mapped_type::iterator minor_it;
// ...
};
iterator begin();
iterator end() {
return { data.end(), /* XXX */ };
}
};
As you see, I want to have iterator implemented for this container. The iterator shall go through each node in map and iterator through each element in the vector the node refers to. I have no problem implementing the iterator, but I had some trouble implementing end()
for the container.
The iterator consists of two levels of iterators, and for the past-end iterator, major_it
will have to be data_t.end()
, but I won't have anything to initialize minor_it
.
In the same vein, begin()
will also be broken when the map is empty.
Any idea?
Upvotes: 1
Views: 92
Reputation: 137780
std::vector::iterator
is always invalid when value-initialized:
std::vector<…>::iterator invalid_iter_value = {};
Incidentally, it's unusable when default-initialized (i.e. uninitialized), which might be good enough for you. If major_it
is already at the end, then simply don't access minor_it
.
std::vector<…>::iterator unusable_iter_value;
However, note that it's also illegal to copy the default-initialized object, so value-initialization is a good idea unless you're customizing the copy constructor and operator.
Upvotes: 3