3

I'm porting a medium-sized C++ project from Visual Studio 2005 to MacOS, XCode / GCC 4.0.

One of the differences I have just stumbled across has to do with erasing an element from a map. In Visual Studio I could erase an element specified by an iterator and assign the return value to the iterator to get the position of the next element. This way the iterator would not point to some invalid address after erasing.

In other words, in Visual Studio I could do this:

itor=m_ResourceMap.erase(itor);

In GCC 4.0, the erase function returns void, so I can't do that. Does that mean that the following map elements are shifted one backwards, so the iterator points automatically to the next element, or does that mean that I have to increment the iterator afterwards? The online STL Documentation is not very concise on the subject and XCode does not seem to have any.

Thanks for your help,

Adrian

Adrian Grigore
  • 33,034
  • 36
  • 130
  • 210

3 Answers3

11

No. You have to increment the iterator before erasing. Like this

m_ResourceMap.erase(itor++);

The iterator is invalidated by the erase, so you can't increment it afterwards.

jpalecek
  • 47,058
  • 7
  • 102
  • 144
  • I'm trying to make sense of the syntax. the itor++ is a postfix increment, so it erases itor, and then it should be invalid anyways, should it not? – Calyth Jan 31 '09 at 02:19
  • 1
    Postfix: increment *and then* return a value of what the iterator used to point to. This value is what gets erased. – Max Lybbert Jan 31 '09 at 09:12
3

By the look of things gcc is following the STL standard so I guess you'll have to change your code.

void erase(iterator pos)     Associative Container  Erases the element pointed to by pos. 
Douglas Leeder
  • 52,368
  • 9
  • 94
  • 137
1

I believe that the DinkumWare implementation of the C++ standard library implementation of erase() is defined to return the iterator after the element that is to be removed. This bit me as well and, when I asked DinkumWare about it, they said that it was a "conforming extension".

There are some STL containers (vectors for instance) that, when you perform insert or erase operations, can tend to invalidate all of the iterators for that container. I cannot recall if the map is one of those but, if it is, there is a potentially insidious vulnerability to your method of erasing map elements in a loop.

Jon Trauntvein
  • 4,453
  • 6
  • 39
  • 69