简体   繁体   中英

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

This is what the code is for: https://www.codechef.com/LRNDSA04/problems/STACKS

Here is the code snippet:

#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;
}

Input to this program is:

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

The Unexpected output it generates:

3 1 1 2
3 5 10 12

If the input is changed to:

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

It shows up correct output:

4 5 10 12 18
3 1 1 2

The test case with 8 numbers as input if its position is altered in the input file. Then this behavior is observed.

When looking at the run of the code via gdb , it gives expected output for both input files, no problem then.

The output is not justified, what am I missing to see?

In this check:

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

if the condition is true, then you are indexing into an invalid position of a , which invokes undefined behavior.

It seems you want to do

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

instead. The conventional way to check for this condition is

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM