gpt4 book ai didi

c++ - 复制 std::string::insert(int pos, char ch)

转载 作者:行者123 更新时间:2023-11-28 04:57:26 24 4
gpt4 key购买 nike

我正在尝试复制 std::string::insert 方法。这是我的代码。

string& string::insert(int pos, char ch)
{
int len = m_length; //the length of the current string
resize(++m_length); //a method to resize the current string(char *)
char *p = m_data + pos; //a pointer to the string's insert position
for (int i = len-1; i >= 0; i--) { //shift characters to the right
p[i+1] = p[i];
}
*p = ch; //assign the character to the insert position
m_data[m_length] = '\0'; //finish the string
return *this;
}

但是,使用代码时,我的应用有时会在向右移动字符时崩溃。

谁能告诉我可能是什么问题以及如何解决它?

非常感谢您!

最佳答案

您移动的字符太多。您只需要移动 len - pos 个字符,而不是 len 个字符。

而且如果在初始化i的时候不减1,那么循环会将已有的null字节移位,所以不需要在最后单独添加。

string& string::insert(int pos, char ch)
{
int len = m_length; //the length of the current string
resize(++m_length); //a method to resize the current string(char *)
char *p = m_data + pos; //a pointer to the string's insert position
for (int i = len - pos; i >= 0; i--) { //shift characters to the right
p[i+1] = p[i];
}
*p = ch; //assign the character to the insert position
return *this;
}

关于c++ - 复制 std::string::insert(int pos, char ch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46858323/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com