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

C++ 将输入文件中的数据位置更改为.cpp程序会意外更改输出,c++,algorithm,C++,Algorithm,这就是代码的用途: 以下是代码片段: #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>

这就是代码的用途:

以下是代码片段:

#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;
}
它生成的意外输出:

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()) {

现在你需要学习一些在线竞赛/评委网站不会教你的东西:调试。在监视变量及其值并查看它们如何变化的同时,使用调试器逐条检查代码。@Someprogrammerdude OP说,当使用
gdb
运行时,它们会得到正确的结果。也许某处有UB。@Someprogrammerdude是的!因此,我已经提到了
gdb
。使用它并一步一步地检查整个代码,gdb运行结束时,
vector a
显示了预期值。只是输出结果不正确。问题不在比较中,而是在作业中,我做了
a[pos]=x
,这是在条件为
pos==a.size()时做的。
错误!将其替换为
a[a.size()-1]=x
,现在一切正常。谢谢。@amarVashishth是的,这就是我的意思,错误的支票导致UB。看看我在答案上的标记。
if(it != a.end()) {