-4

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

  • 2
    Your code only demonstrates a lot of bad habits. – 273K Feb 04 '23 at 06:05
  • 1
    Obligatory reminder: [Why should I not #include ?](https://stackoverflow.com/q/31816095/2752075) and [Why should I not #include ?](https://stackoverflow.com/q/31816095/2752075). The macros make this very hard to read too. I'd suggest removing macros when posting here (or not using them at all; you'll have to unlearn this habit when you get a job anyway). – HolyBlackCat Feb 04 '23 at 06:08
  • Enable iterator debugging (on GCC it's done with `-D_GLIBCXX_DEBUG`). This will give you a better error when misusing them. Then use debugger to see on what line the error happens. – HolyBlackCat Feb 04 '23 at 06:12
  • `w.erase(it);` makes no sense. The `end()` iterator cannot be used like that. – Retired Ninja Feb 04 '23 at 06:13
  • *"immediately terminates"* -- What debugging did you do to determine that the program terminates immediately after the loop that populates `a`, meaning just before the line `int mx = 0;` would execute? If you have not actually determined this, then please don't mis-characterize your symptom as "immediately". Rather, *"terminates at some point before the output, but I have not narrowed down the point of termination any further (despite the ease of adding diagnostic output)"* is more accurate. Even a line like `std::cout << "Starting loop " << i << '\n';` at the start of your loop would help. – JaMiT Feb 04 '23 at 08:24

1 Answers1

1

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);
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770