[xsd-users] Erasing elements
Boris Kolpackov
boris at codesynthesis.com
Mon May 8 03:36:47 EDT 2006
Hi Andrew,
Andrew Ward <andy.ward at hevday.com> writes:
> int main()
> {
> hello_type ht("hi");
> ht.name().push_back("1");
> ht.name().push_back("2");
> ht.name().push_back("3");
>
> hello_type::name::iterator it(ht.name().begin()), end(ht.name().end());
>
> while(it != end)
> {
> std::cout << "erasing " << (*it) << std::endl;
> it = ht.name().erase(it);
> if(it != end)
> std::cout << (*it) << " comes next" << std::endl;
> else
> std::cout << "all erased" << std::endl;
> }
> }
>
> After "3" is erased "it != end" still evaluates to true and the program
> crashes. Is this code valid and is there an alternative?
XSD sequence containers behave like (and, in fact, are based on)
std::vector (Section 2.8.3 of the manual) which does not guarantee
iterator stability for the erase operation (unlike std::list). This
means that you cannot cache the end position as you did above. Instead,
you will need to write:
while(it != ht.name().end())
{
std::cout << "erasing " << (*it) << std::endl;
it = ht.name().erase(it);
if(it != ht.name().end())
std::cout << (*it) << " comes next" << std::endl;
else
std::cout << "all erased" << std::endl;
}
After this change, your example prints:
erasing 1
2 comes next
erasing 2
3 comes next
erasing 3
all erased
hth,
-boris
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 652 bytes
Desc: Digital signature
Url : http://codesynthesis.com/pipermail/xsd-users/attachments/20060508/32a345dc/attachment.pgp
More information about the xsd-users
mailing list