简体   繁体   English

仅通过迭代器删除STL容器元素

[英]Deleting STL-container element via iterator only

Is there a way to delete an element from an STL container (be it list , vector , ...) only via an iterator pointing to the element to be deleted, but without providing the container object it resides in (ie without directly using the container memberfunction container<T>::iterator container<T>.erase(container<T>::iterator) ? 有没有一种方法可以仅通过指向要删除元素的迭代器从STL容器中删除元素(它为listvector ,...),但提供其驻留的容器对象(即不直接使用容器成员函数container<T>::iterator container<T>.erase(container<T>::iterator)吗?

(Follow-up to this question ) 此问题的跟进)

No, this is not possible. 不,这是不可能的。

Imagine what would have to happen in order for the standard to provide a way to do this. 想象一下,为了使标准提供一种执行此操作的标准,将会发生什么。 std::vector<T>::iterator could not be a simple T* . std::vector<T>::iterator不能是简单的T* Instead it would have to contain enough information for the library to be able to "find" the vector to which it belongs, such as a pointer to the vector itself. 相反,它必须包含足够的信息以使库能够“查找”它所属的向量,例如指向向量本身的指针。 Thus, if the standard imposed a requirement to make it possible to delete an element given only an iterator, it would force the standard library to add overhead that would slow down all users of the container. 因此,如果标准强加了仅允许删除迭代器就可以删除元素的要求,那么它将迫使标准库增加开销,从而减慢容器的所有用户的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM