c++ - 模棱两可的运行时错误,导致程序立即崩溃

标签 c++ crash runtime

#include <bits/stdc++.h>

using namespace std;
int freq[101034];
int main() {

  int n;
  cin >> n;
  set<int> st;
  for (int i = 0; i < n; i++) {
    int x;
    cin >> x;
    freq[x]++;
    st.insert(x);
  }
  while (!st.empty()) {
    for (auto x : st) {
      if (freq[x] <= 0) {
        st.erase(x);
        continue;
      }
      cout << x << ' ';
      freq[x]--;
    }
    cout << '\n';
  }
  return 0;
}

我试图解决的问题:给定一个整数数组n10^5,每个元素到10^5,任务是打印没有重复的排序数组,然后删除打印的数组元素,然后重复直到该数组被空的。

例如,如果数组[1、1,2、3、4、4]
这应该打印
1 2 3 4 
1 4

我维护了一个频率数组来保存每个元素的频率,并且上面的代码导致运行时错误。程序崩溃。我试图删除if语句,程序正常运行,但可以肯定地进入无限循环!我真的不知道为什么if会导致运行时错误。

最佳答案

问题在以下代码段中:

while (!st.empty()) {
    for (auto x : st) {
      if (freq[x] <= 0) {
        st.erase(x);
        continue;
      }
      cout << x << ' ';
      freq[x]--;
    }
    cout << '\n';
}

基于范围的for循环在后面使用迭代器(有关更多详细信息,请参见this)。当您从x中删除st时,循环迭代器(指向x)变得无效(这意味着您不再可以使用它),但是在上面的代码段中,它仍在后台循环的末尾递增,导致 undefined 的行为,从而导致运行时错误。

看一看this page,看看如何正确实现它。将上一个链接的实践应用于您的代码:
while (!st.empty()) {
    for (auto it = cbegin(st); it != cend(st);) {
        auto x = *it;
        if (freq[x] <= 0) {
            it = st.erase(it);
        } else {
            ++it;
            cout << x << ' ';
            freq[x]--;
        }
    }
    cout << '\n';
}

关于c++ - 模棱两可的运行时错误,导致程序立即崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59729804/

相关文章:

c++ - 使用 GDI+ 和 C++ 将 JPEG 编码的屏幕截图保存到缓冲区

java - 来自类变量的 JNI jstring?

c++ - 插入一个元素到柠檬图库 map 而不复制

c++ - 为什么我的程序在运行这个特定功能后会崩溃?

c++ - 在 vector C++ 上操作时出现运行时断言错误

c++ - 最好在类中的堆栈或堆上分配

android - 在启动应用程序时会在android wix react-native-navigation抽屉中崩溃,但在iOS上工作正常

php - 当我通过具有空值的 PHP web 服务发布 JSON 数据时,Iphone 应用程序崩溃

iOS WebView WTF 崩溃

javascript - 在运行时获取 node.js 版本