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

为何unordered_map无法正确显示字符串字符的出现索引值?

问题分析:字符串索引存储错误排查

问题描述

我需要将字符串"codeforces"中的字符作为unordered_map的键,把字符出现的1-based索引存入vector作为对应值。其中字符'c'预期出现在索引1和8的位置,但程序实际输出仅为7,无法得到正确结果。

原代码

#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

int main(){ 
    string x = "codeforces";
    unordered_map<char,vector<int>> data;

    for(int i = 1;i <= x.size();i++){
        data[x[i]].push_back(i);
    }

    for(auto it : data){
        if(it.first == 'c'){
            vector<int> out = it.second;
            for(int j = 0;j < out.size();j++){
                cout<<out[j]<<" ";
            }
            cout<<endl;
        }
    }

    return 0;
}

错误原因

  1. 索引访问逻辑错误
    C++字符串的索引是0-based(从0开始计数),你的循环从i=1开始,到i<=x.size()结束:
    • 第一个'c'在原字符串的0-based索引是0,但循环从未访问x[0],导致这个字符完全没被存入map;
    • 当i=x.size()时(x.size()为10),x[10]属于越界访问,会触发未定义行为;
    • 第二个'c'在原字符串的0-based索引是7,对应你预期的1-based索引8,但你循环中i=8时访问的是x[8](字符'e'),只有i=7时才会访问到x[7]('c'),所以存入的索引是7,这就是你看到的输出结果。

修正方案

有两种可行的修正方式,都能得到预期的1 8输出:

方式一:使用0-based循环,存储1-based索引

#include <iostream>
#include <unordered_map>
#include <vector>
#include <string>
using namespace std;

int main(){ 
    string x = "codeforces";
    unordered_map<char,vector<int>> data;

    for(int i = 0; i < x.size(); i++){
        data[x[i]].push_back(i + 1); // 将0-based索引转为1-based存入
    }

    for(auto &it : data){
        if(it.first == 'c'){
            for(int idx : it.second){
                cout << idx << " ";
            }
            cout << endl;
        }
    }

    return 0;
}

方式二:使用1-based循环,访问正确的字符位置

#include <iostream>
#include <unordered_map>
#include <vector>
#include <string>
using namespace std;

int main(){ 
    string x = "codeforces";
    unordered_map<char,vector<int>> data;

    for(int i = 1; i <= x.size(); i++){
        data[x[i-1]].push_back(i); // 通过i-1访问0-based的字符位置
    }

    for(auto &it : data){
        if(it.first == 'c'){
            for(int idx : it.second){
                cout << idx << " ";
            }
            cout << endl;
        }
    }

    return 0;
}

内容的提问来源于stack exchange,提问作者Study Planet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:30:57