【问题标题】:Why does vector::erase seem to cause a crash?为什么 vector::erase 似乎会导致崩溃?
【发布时间】:2019-12-23 16:40:52
【问题描述】:

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

【问题讨论】:

  • 没有第二个循环,否则first1 的大小为4,second 的大小为2
  • 在迭代容器时修改容器是个坏主意。我建议拆分操作。复制然后擦除。
  • 您的问题标题与您报告的内容不符。您的程序不会“崩溃”。
  • 在可能的情况下进行迭代时,我忘了远离修改容器......我一直没有睡好,所以我的头脑有点不稳定
  • 我的困惑是因为代码到达了std::cout 语句并产生了输出,而不是你所期望的。通常,“崩溃”意味着程序停止或异常终止,可能显示错误或异常。

标签: c++ loops for-loop vector erase


【解决方案1】:

循环的第一次迭代之后

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 个元素。

【讨论】:

    猜你喜欢
    • 2020-02-15
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多