删除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。因此,仅擦除了 vector 的一个元素。

您可以像这样重写循环
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个元素。

09-07 03:45