在 C++ 中创建erase() 函数的自制副本

问题描述

我正在尝试使用以下代码创建一个函数来执行内置函数 .erase() 在 C++ 中所做的事情:

string delChar(string text,int no_of_ch_to_delete,int starting_point)
{
    int Final_Point = starting_point + no_of_ch_to_delete;
    for (int i = starting_point; i <= Final_Point; i++)
    {
        text = text.at(i) = '\0';
    }
    return text;
}

这给了我一个我无法弄清楚的错误:

Unhandled exception thrown: write access violation.
std::basic_string<char,std::char_traits<char>,std::allocator<char> >::at(...) returned 0xCD9CC6C4.

我该如何纠正?

解决方法

这一行:

text = text.at(i) = '\0';

实际上与

相同
text.at(i) = '\0';
text = '\0';

最后一行用单个字符 text 替换字符串 \0 的任何内容。 text 现在有 1 元素,通过 at(i) 进行的任何进一步访问都是越界的。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...