Map Iterator for Round Robin selection along with Map Updates

V

Vikram Karandikar

Hi all,

I have class something like this

class Y
{
....
};

class X
{
public:
map <uint32_t, Y *> yList;
map <uint32_t, Y *>::iterator yListIter;

X ()
{
yListIter = yList.begin ();
}

add (Y *obj)
{
yList [obj->key] = obj;
}
}

Program

X x;
map <uint32_t, Y *>::iterator i1;

x.add (new Y (1));
i1 = x.yListIter;
x.add (new Y(2));

My question is can i safely assume that i1 is always valid if there are only new things getting added to the map?

If delete is going to happen i will reset if to begin.

Thanks in advance.
 
V

Vikram Karandikar

Vikram Karandikar writes:


Hi all,

I have class something like this

class Y




class X


map <uint32_t, Y *> yList;
map <uint32_t, Y *>::iterator yListIter;
X ()

yListIter = yList.begin ();

add (Y *obj)

yList [obj->key] = obj;

X x;
map <uint32_t, Y *>::iterator i1;

x.add (new Y (1));
i1 = x.yListIter;
x.add (new Y(2));

My question is can i safely assume that i1 is always valid if there are only
new things getting added to the map?



Well, yes, however your constructor calls begin() on an empty list, which

returns the ending iterator value, the end() value, and puts it into

yListIter.



After adding the first element to the list, your yListIter will still point

to the end() value, not the first value of the list.



std::map::begin() does not return an iterator value that will always

dereference to the first element in the map, or end(). It returns an

iterator value that dereferences to the first element in the map, or end(),

at the time that begin() was invoked. If another element gets added to the

map with the lowest key value of any existing element in the map, and thus

it becomes the new first element in the map, dereferencing what begin()

returned previously will not give you the current first element in the map.



So, although your code, above is well-formed, it's not going to do what you

appear to want it to do.



Thanks Sam for your reply. I understood what you want to say.
Suppose i had the iterator set to one of the elements present in the map (not to the begin of empty map), then will updates to the map make the iterator invalid?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top