هل يمكنني الاستمرار في استخدام المكرر بعد حذف عنصر من std::multimap<>؟[ينسخ]

StackOverflow https://stackoverflow.com/questions/446205

  •  22-07-2019
  •  | 
  •  

سؤال

هل يمكنني الاستمرار في استخدام مكرر multimap حتى بعد الاتصال بـ multimap::erase()؟على سبيل المثال:

Blah::iterator iter;
for ( iter = mm.begin();
      iter != mm.end();
      iter ++ )
{
    if ( iter->second == something )
    {
        mm.erase( iter );
    }
}

هل من المتوقع أن يعمل هذا بشكل صحيح، أم أن المكرر تم إبطاله بعد استدعاء المسح؟المواقع المرجعية مثل http://www.cplusplus.com/reference/stl/multimap/erase.html نحن هادئون بشكل غريب بشأن هذا الموضوع المتعلق بعمر التكرارات، أو تأثيرات الأساليب البناءة/المدمرة على التكرارات.

هل كانت مفيدة؟

المحلول

http://www.sgi.com/tech/stl/Multimap.html

Multimap has the important property that inserting a new element
into a multimap does not invalidate iterators that point to existing
elements. Erasing an element from a multimap also does not invalidate
any iterators, except, of course, for iterators that actually point to
the element that is being erased.

لذلك يجب أن يبدو مثل هذا:

Blah::iterator iter;
for ( iter = mm.begin();iter != mm.end();)
{
    if ( iter->second == something )
    {
        mm.erase( iter++ );
        // Use post increment. This increments the iterator but
        // returns a copy of the original iterator to be used by
        // the erase method
    }
    else
    {
        ++iter;   // Use Pre Increment for efficiency.
    }
}

انظر أيضا:ماذا يحدث إذا قمت باستدعاء ()erase على عنصر الخريطة أثناء التكرار من البداية إلى النهاية؟

و

حذف إدخال محدد في الخريطة، ولكن يجب أن يشير المكرر إلى العنصر التالي بعد الحذف

نصائح أخرى

معيار C++ 23.1.2.8:

The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.

يعد هذا متطلبًا شائعًا لجميع الحاويات الترابطية، وstd::multimap هو أحدها.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top