You need to enable JavaScript to run this app. C++运行抛std::out_of_range异常substr调用错误问题求解
优惠活动
大模型
产品
解决方案
定价
更多

C++运行抛std::out_of_range异常substr调用错误问题求解

填字游戏开发问题排查

问题需求

现有填字游戏开发需求:共m行填空,每个线索最多n个单词,3≤m,n≤100。输入第一行是m、n,接下来m行是填字游戏模板,其中1代表待填位置,0代表无需填充位置,已给出的字母为固定字符;再接下来m行是线索词,要求输出填充完成后的填字游戏结果。

报错信息

代码运行直接终止,抛出错误:
terminate called after throwing an instance 'std::out_of_range' what(): basic_string::substr: __pos > this->size()

输入输出样例

输入样例

3 8
011G1100
1A111000
00000C11
CAT
NIGHT
DOG

期望输出样例

0NIGHT00
CANDY000
00000CAT

问题根因

以下是代码中存在的所有问题,按触发报错的优先级排序:

  • 第一,vector初始化逻辑错误:你定义vector <string> map(m)的时候已经预创建了m个空字符串,后续循环又执行push_back操作,最终vector实际长度为2m,前m个元素都是空字符串。后续循环取map[i]的时候取到空字符串,find_first_not_of("0")会返回string::npos(无效索引),传入substr就直接触发越界报错,这是你遇到的报错的直接原因。
  • 第二,索引使用错误:C++的vector、字符串都是0索引,你所有循环都从i=1跑到i<=m,会访问到索引为m的越界元素,合法索引范围是0~m-1。
  • 第三,遍历字符串逻辑错误:for(int k =0;k<= str3.length();k++)里的<=要改成<,字符串的索引最大是长度-1,否则也会触发越界。
  • 第四,匹配逻辑错误:当前只要有一个字符匹配就替换,正确逻辑应该是模板里所有非1的固定字符,都和线索对应位置的字符完全一致,才算匹配成功。
  • 第五,输出逻辑错误:替换后没有输出换行,且break只跳出了内层k循环,会导致同一行重复输出多次。

修复后的参考代码

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main() {
    int m, n;
    cin >> m >> n;
    // 不混用预分配和push_back逻辑,避免产生空元素
    vector<string> map;
    vector<string> clue;
    map.reserve(m);
    clue.reserve(m);

    for (int i = 0; i < m; i++) {
        string dd;
        cin >> dd;
        map.push_back(dd);
    }
    for (int i = 0; i < m; i++) {
        string dd;
        cin >> dd;
        clue.push_back(dd);
    }

    for (int i = 0; i < m; i++) {
        string str = map[i];
        int pos = str.find_first_not_of("0");
        int pos2 = str.find_last_not_of("0");
        int len = pos2 - pos + 1;
        string pattern = str.substr(pos, len);

        // 遍历所有线索找匹配项
        for (int j = 0; j < m; j++) {
            string cur_clue = clue[j];
            if (cur_clue.length() != len) continue;

            bool match = true;
            for (int k = 0; k < len; k++) {
                if (pattern[k] != '1' && pattern[k] != cur_clue[k]) {
                    match = false;
                    break;
                }
            }

            if (match) {
                str.replace(pos, len, cur_clue);
                cout << str << endl;
                // 标记线索已用避免重复匹配
                clue[j] = "";
                break;
            }
        }
    }
    return 0;
}

内容的提问来源于stack exchange,提问作者Huỳnh Thiên Bảo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 08:54:05