1. 程式人生 > >叠代器失效

叠代器失效

end ast first xtra memory emp lac 代碼 spec

關於叠代器失效的問題,我們先從LeetCode上面的一道題說起。

題目:

Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

示例:

Given nums = [1
,1,2], Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesnt matter what you leave beyond the new length.

小子給出的函數代碼為:

int removeDuplicates(vector<int>& nums) 
{
int last = 0; int length = 1; if (nums.empty()) {
return 0; } for (auto i = nums.begin(); i != nums.end(); ) { if ( i == nums.begin()) { last = *i; ++i; continue; } if (*i == last) { i = nums.erase(i);//註意叠代器失效 } else { last
= *i; ++length; ++i; } } return length; }

在上面代碼中需要註意的就是註釋的那附近。

因為叠代器在刪除或者添加元素會使舊叠代器後面的叠代器都失效,叠代器的工作原理是將原容器等操作後結果復制到一個新的容器中。若當前元素被刪除,那麽該元素的叠代器會失效,如果用戶還對當前元素進行自增等操作,這是不允許的。

所以正確的操作是,若當前操作是改變容器的長度等會產生叠代器失效的操作,那麽對當前叠代器不能使用自增或其他操作。對於後面的元素,可通過erase()返回的叠代器進行操作。

以上代碼若忽略叠代器失效,部分代碼為:

if (*i == last)
{
  i = nums.erase(i);
  ++i;//叠代器失效
}
else
{
  ++length;
  last = *i;
}

在《C++ Primer》(中文版)這本書的第315頁,也說到了很多容器操作可能導致叠代器失效的一些內容。

以上為個人愚見,歡迎指正。

叠代器失效