J
jose luis fernandez diaz
Hi,
Erase elements while iterating on a map don't invalidate the iterator
except the erased one, so the program below:
(1)
#include <map>
int main()
{
map<int, int> m1;
m1[1]=1;
m1[2]=2;
m1[3]=3;
m1[4]=4;
m1[5]=5;
map<int,int>::iterator it;
srandom(time(0));
for (it=m1.begin(); it!= m1.end();it++)
{
if (random()%2)
{
m1.erase(it->first);
}
}
return 0;
}
would be:
(2)
.. . .
for (it=m1.begin(); it!= m1.end()
{
int erase_element = it->first;
++it;
if (random()%2)
{
m1.erase(erase_element);
}
}
.. . .
I think that the first program (1) is more intuitive and elegant that
the second (2).
Why the first program is not valid ?
Thanks,
Jose Luis.
Erase elements while iterating on a map don't invalidate the iterator
except the erased one, so the program below:
(1)
#include <map>
int main()
{
map<int, int> m1;
m1[1]=1;
m1[2]=2;
m1[3]=3;
m1[4]=4;
m1[5]=5;
map<int,int>::iterator it;
srandom(time(0));
for (it=m1.begin(); it!= m1.end();it++)
{
if (random()%2)
{
m1.erase(it->first);
}
}
return 0;
}
would be:
(2)
.. . .
for (it=m1.begin(); it!= m1.end()
{
int erase_element = it->first;
++it;
if (random()%2)
{
m1.erase(erase_element);
}
}
.. . .
I think that the first program (1) is more intuitive and elegant that
the second (2).
Why the first program is not valid ?
Thanks,
Jose Luis.