You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无语法错误的C++程序读取输入后立即终止,求问题排查方案

问题分析与修复

你的程序读取输入后立即终止是因为逻辑错误引发的未定义行为:

  • 当find(w.begin(), w.end(), a[i])返回的迭代器it != w.end()时,说明元素a[i]已存在于w中,但你却执行了w.push_back(a[i])(重复添加);
  • 当it == w.end()时,元素不在w中,你却尝试执行w.erase(it)——erase仅接受指向容器内有效元素的迭代器,传入end()迭代器属于未定义行为,直接触发程序崩溃。

修正后的代码

#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++)
    {
        auto it = find(w.begin(), w.end(), a[i]);
        if (it != w.end())
        {
            // 元素存在,移除它
            w.erase(it);
        }
        else
        {
            // 元素不存在,添加它
            w.push_back(a[i]);
        }
        mx = max(mx, (int)w.size());
    }
    
    cout << mx << endl;
    return 0;
}

额外优化建议

使用vector的find操作时间复杂度为O(k)(k为当前vector大小),若数据量较大,建议改用unordered_set实现O(1)的查找效率,同时用变量跟踪当前集合大小:

#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, current_size = 0;
    unordered_set<int> s;
    for (int num : a)
    {
        if (s.count(num))
        {
            s.erase(num);
            current_size--;
        }
        else
        {
            s.insert(num);
            current_size++;
        }
        mx = max(mx, current_size);
    }
    
    cout << mx << endl;
    return 0;
}

内容的提问来源于stack exchange,提问作者Zeyad Galal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 15:55:17