#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;
}
我试图解决的问题:给定一个整数数组
n
到10^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/