Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Running a C++ code with no syntax error but something strange terminates

My code has something strange. It doesn’t have any syntax errors, and when I run it, it runs and takes input, and then immediately terminates. What is the issue?

I have tried to run the code in VS Code and Codeblocks, and I am faced with the same error. I am stuck right now.

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin >> n;
    vector<int>a(2 * n);
    for (int i = 0;i < 2 * n;i++)
    {
        cin >> a[i];
    }
    int mx = 0;
    vector<int>w;
    for (int i = 0;i < 2 * n;i++)
    {
        vector<int>::iterator it = find(w.begin(), w.end(), a[i]);
        if (it != w.end())
        {
            w.push_back(a[i]);
        }
        else
        {
            w.erase(it);
        }
        if (mx < w.size())
        {
            mx = w.size();
        }
    }
    cout << mx << endl;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In your 2nd loop, you are calling w.erase(it) when it is w.end(), which is undefined behavior:

https://en.cppreference.com/w/cpp/container/vector/erase

The iterator pos must be valid and dereferenceable. Thus the end() iterator (which is valid, but is not dereferenceable) cannot be used as a value for pos.

You are trying to push the integer if it is found, and erase it if it is missing. That logic is backwards. You need to use == instead of != in your if condition to reverse the logic:

if (it == w.end()) // <--
{
    w.push_back(a[i]);
}
else
{
    w.erase(it);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading