更改.cpp程序的输入文件中数据的位置会意外更改输出

Changing position of data in Input file to a .cpp program Changes output unexpectedly

本文关键字:意外 位置 输出 程序 cpp 输入 文件 更改 数据      更新时间:2023-10-16

这就是代码的用途:https://www.codechef.com/LRNDSA04/problems/STACKS

以下是代码片段:

#include<bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t; cin >> t;
while (t--)
{
int n; cin >> n;
vector<int> a;
while(n--) {
int x; cin >> x;
if(a.empty()) {
a.push_back(x);
} else {
vector<int>::iterator it = upper_bound(a.begin(), a.end(), x);
int pos = it - a.begin();
if(pos == a.size()) {
if(a[pos] > x) {
a[pos] = x;
} else {
a.push_back(x);
}
} else {
a[pos] = x;
}
}
}
cout << a.size();
for(auto e: a) {
cout << " " << e;
}
cout << "n";
}

return 0;
}

该程序的输入为:

2
6
3 4 5 1 1 2
8
14 5 13 19 17 10 18 12

它生成的意外输出:

3 1 1 2
3 5 10 12

如果输入更改为:

2
8
14 5 13 19 17 10 18 12
6
3 4 5 1 1 2

它显示正确的输出:

4 5 10 12 18
3 1 1 2

如果8个数字在输入文件中的位置发生更改,则将其作为输入的测试用例。然后观察到这种行为。

当通过gdb查看代码的运行时,它会为两个输入文件提供预期的输出,这是没有问题的。

输出不合理,我缺少什么?

在此检查中:

if(pos == a.size()) {
if(a[pos] > x) {   // this is UB

如果条件为true,则索引到a的无效位置,这将调用未定义的行为。

看来你想做

if(pos != a.size()) {

相反。检查这种情况的常规方法是

if(it != a.end()) {