为什么 g++ 4.0 版本的 map::erase(map::iterator) 不返回迭代器?
我正在将一个中型 C++ 项目从 Visual Studio 2005 移植到 MacOS、XCode / GCC 4.0。
我刚刚偶然发现的差异之一与从地图中删除元素有关。 在 Visual Studio 中,我可以删除迭代器指定的元素,并将返回值分配给迭代器以获取下一个元素的位置。 这样迭代器在擦除后就不会指向某些无效地址。
换句话说,在 Visual Studio 中我可以这样做:
itor=m_ResourceMap.erase(itor);
在 GCC 4.0 中,擦除函数返回 void,所以我不能这样做。 这是否意味着后面的映射元素向后移动一个,因此迭代器自动指向下一个元素,或者这是否意味着我必须在之后增加迭代器? 在线 STL 文档 在这个主题上不是很简洁,XCode 似乎也不是有任何。
感谢您的帮助,
阿德里安
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不可以。您必须在擦除之前递增迭代器。 像这样
迭代器会因擦除而失效,因此之后无法递增它。
No. You have to increment the iterator before erasing. Like this
The iterator is invalidated by the erase, so you can't increment it afterwards.
从表面上看,gcc 遵循 STL 标准,所以我猜你必须更改你的代码。
By the look of things gcc is following the STL standard so I guess you'll have to change your code.
我相信 Ease() 的 C++ 标准库实现的 DinkumWare 实现被定义为在要删除的元素之后返回迭代器。 这也让我很恼火,当我向 DinkumWare 询问此事时,他们说这是一个“符合要求的扩展”。
有一些 STL 容器(例如向量),当您执行插入或擦除操作时,可能会导致该容器的所有迭代器无效。 我不记得地图是否是其中之一,但如果是,则您在循环中擦除地图元素的方法存在潜在的潜在漏洞。
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.