[英]Creating a self-made replica of the erase() function in C++
I am trying to create a function to do what the built-in function .erase()
does in c++ with the following code:我正在尝试创建一个 function 来执行内置 function
.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;
}
This is giving me an error that I am unable to figure out:这给了我一个我无法弄清楚的错误:
Unhandled exception thrown: write access violation.
std::basic_string<char,std::char_traits<char>,std::allocator<char> >::at(...) returned 0xCD9CC6C4.
How can I correct this?我该如何纠正?
This line:这一行:
text = text.at(i) = '\0';
is effectively the same as实际上与
text.at(i) = '\0';
text = '\0';
The last line replaces any contents of the string text
with the single character \0
.最后一行用单个字符
\0
替换字符串text
的任何内容。 text
has now 1
element and any further access via at(i)
is out-of-bounds. text
现在有1
元素,并且通过at(i)
进行的任何进一步访问都是越界的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.