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;
}
>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 theend()
iterator (which is valid, but is not dereferenceable) cannot be used as a value forpos
.
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);
}