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

如何基于字符串原始索引删除单个字符?现有代码遇段错误求修复

修复按原始索引删除字符串字符时的段错误问题

假设我有字符串abcd和索引向量[4,1,3,2],需要按向量中的原始索引依次删除字符,每次操作后记录字符串状态。以下是我写的C++代码:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int m;
    cin >> m;
    string T;
    cin >> T;
    cout << T << endl;
    vector<int> arr(m);
    for(auto &x : arr) cin >> x;
    // Remove character from string at given index position
    for (int i = 0; i < m; i++){
        T.erase(T.begin() + arr[i]-1);
        cout << T << endl;
    }
    return 0;
}

运行时出现异常,输出如下:

4
abcd
abcd
4 1 3 2
abc
bc
Segmentation fault

问题原因

每次删除字符后,字符串长度会缩短,但代码仍然直接使用原始字符串的索引计算删除位置,导致后续操作出现索引越界。比如第三次删除时,原索引是3(转换为0-based是2),但此时字符串已经缩短为bc(长度仅为2),T.begin()+2已经超出字符串的有效范围,触发段错误。

修复方案

方案一:计算当前有效位置

通过标记数组记录原始字符是否已被删除,每次计算目标原始字符在当前字符串中的实际位置,确保删除操作不会越界:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int m;
    cin >> m;
    string T;
    cin >> T;
    cout << T << endl;
    
    vector<int> original_indices(m);
    for(auto &x : original_indices) {
        cin >> x;
        x--; // 转换为0-based索引
    }
    
    vector<bool> deleted(T.size(), false); // 标记原始字符是否已被删除
    string current = T;
    
    for(int idx : original_indices) {
        if(deleted[idx]) {
            cout << current << endl;
            continue;
        }
        // 计算目标字符在当前字符串中的位置
        int pos = 0;
        for(int i = 0; i < idx; ++i) {
            if(!deleted[i]) pos++;
        }
        current.erase(current.begin() + pos);
        deleted[idx] = true;
        cout << current << endl;
    }
    
    return 0;
}

方案二:按逆序删除原始索引

利用“删除大索引不会影响小索引位置”的特性,先按原始索引从大到小执行删除操作,再按原始顺序输出每次操作后的状态:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    int m;
    cin >> m;
    string T;
    cin >> T;
    cout << T << endl;
    
    vector<pair<int, int>> ops;
    for(int i = 0; i < m; ++i) {
        int x;
        cin >> x;
        ops.emplace_back(x-1, i); // 存储(0-based原始索引, 操作顺序)
    }
    
    // 按原始索引从大到小排序,避免删除操作影响后续位置计算
    sort(ops.begin(), ops.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
        return a.first > b.first;
    });
    
    string temp = T;
    vector<string> op_states(m);
    
    for(auto& op : ops) {
        temp.erase(temp.begin() + op.first);
        op_states[op.second] = temp;
    }
    
    // 按原始操作顺序输出状态
    for(int i = 0; i < m; ++i) {
        cout << op_states[i] << endl;
    }
    
    return 0;
}

测试结果

输入:

4
abcd
4 1 3 2

输出:

abcd
abc
bc
b

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 12:16:04