簡體   English   中英

為什么 vector::erase 似乎會導致崩潰?

[英]Why does vector::erase seem to cause a crash?

first1.erase(std::next(first1.begin(), i)); 刪除了第二個循環,它有點奇怪,因為first2.erase(first2.begin() + 4, first2.end()); 工作正常

#include <iostream>
#include <vector>

int main ()
{
    std::vector<int> first1 = {0,1,2,3,4,5};
    std::vector<int> first2 = {0,1,2,3,4,5};
    std::vector<int> second;
    std::vector<int> third;

    for(size_t i = 4; i < first1.size(); ++i){
      auto child = first1[i];
      second.push_back(child);
      first1.erase(std::next(first1.begin(), i));
    }

    third.assign(first2.begin() + 4, first2.end());
    first2.erase(first2.begin() + 4, first2.end());

    std::cout << "Size of first: " << int (first1.size()) << '\n';
    std::cout << "Size of second: " << int (second.size()) << '\n';
    std::cout << "Size of first: " << int (first2.size()) << '\n';
    std::cout << "Size of third: " << int (third.size()) << '\n';
    return 0;
}

輸出:

Size of first1: 5
Size of second: 1
Size of first2: 4
Size of third: 2

我希望first1/secondfirst2/third相同

你可以在這里測試它http://cpp.sh/9ltkw

在循環的第一次迭代之后

for(size_t i = 4; i < first1.size(); ++i){
  auto child = first1[i];
  second.push_back(child);
  first1.erase(std::next(first1.begin(), i));
}

i將等於5而 first1.size() 也將等於 5。因此,僅擦除向量的一個元素。

你可以像這樣重寫循環

for(size_t i = 4; i != first1.size(); ){
  auto child = first1[i];
  second.push_back(child);
  first1.erase(std::next(first1.begin(), i));
}

以獲得預期的結果。

在這些聲明中

third.assign(first2.begin() + 4, first2.end());
first2.erase(first2.begin() + 4, first2.end());

有分配和擦除 2 個元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM