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

C++向量a[1]输出异常求助:循环可输出但直接访问失效

问题排查与修复

核心问题1:比较函数cmp存在未定义行为

你的cmp函数在两个字符串完全相等时没有返回值,这会导致sort函数执行时出现未定义行为——排序结果混乱、甚至程序崩溃。C++要求bool类型的函数必须在所有代码路径都返回值。

修复后的cmp函数:

bool cmp(string x, string y){
    if(x.size() != y.size()) 
        return x.size() < y.size();
    else{
        for(int i=0; i<x.size(); i++){
            if(x[i] != y[i]) 
                return x[i] < y[i];
        }
        // 字符串完全相等时返回false(逻辑一致即可,不影响排序稳定性)
        return false;
    }
}

核心问题2:字符提取逻辑错误,vector混入空字符串

原代码遇到非数字字符就直接push当前s1,但初始s1为空,连续非数字字符会多次向vector中插入空字符串。这会导致a[1]可能是空字符串,所以cout输出时看不到内容;而for循环遍历会输出所有元素(包括空串),你看到的有效内容其实是其他非空元素的拼接,误以为循环正常。

修复后的提取逻辑(仅收集非空的数字串):

while(i < s.length()){
    if(isdigit(s[i])){
        s1 += s[i];
        i++;
    }
    else{
        // 仅当s1不为空时才插入vector
        if(!s1.empty()){
            a.push_back(s1);
            s1.clear();
        }
        i++;
    }
}

核心问题3:未检查vector大小就访问a[1]

即使修复了前两个问题,如果输入中数字串的数量不足2,直接访问a[1]会触发越界访问,导致未定义行为。必须先判断vector的大小:

if(a.size() >= 2){
    cout << a[1];
} else {
    // 可选:处理元素不足的情况
    cout << "Insufficient elements in vector";
}

完整修复后的代码

#include <bits/stdc++.h>
using namespace std;

string s, s1;
vector<string> a;

bool cmp(string x, string y){
    if(x.size() != y.size()) 
        return x.size() < y.size();
    else{
        for(int i=0; i<x.size(); i++){
            if(x[i] != y[i]) 
                return x[i] < y[i];
        }
        return false;
    }
}

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    
    cin >> s;
    s += ' ';
    int i = 0;
    
    while(i < s.length()){
        if(isdigit(s[i])){
            s1 += s[i];
            i++;
        }
        else{
            if(!s1.empty()){
                a.push_back(s1);
                s1.clear();
            }
            i++;
        }
    }
    
    sort(a.begin(), a.end(), cmp);
    
    if(a.size() >= 2){
        cout << a[1];
    } else {
        cout << "Insufficient elements in vector";
    }
    
    cout << s[0];
    for(int x=1; x<s.size()-1; x++){
        if(!isdigit(s[x])) {
            cout << s[x];
        }
    }

    return 0;
}

内容的提问来源于stack exchange,提问作者Hà Anh Tiến

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 00:15:03