【问题标题】:Replicating std::string::insert(int pos, char ch)复制 std::string::insert(int pos, char ch)
【发布时间】:2017-10-20 22:48:41
【问题描述】:

我正在尝试复制 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;
}

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

谁能指出可能是什么问题以及如何解决它?

非常感谢您!

【问题讨论】:

  • 如果这是你的实际代码,你的调整大小应该是resize(m_length +1),否则你实际上将 m_length 增加了 1,这将导致 m_data[m_length] = '\0'; 除了导致其他问题之外。虽然我需要看到resize 才能确定...
  • @Zack Lee This loop for (int i = len-1; i >= 0; i--) { //向右移动字符 p[i+1] = p[i] ; } 没有意义。您必须从该位置开始移动元素。那就是表达式 p + len 可以在字符串之外。

标签: c++ string pointers


【解决方案1】:

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

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

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;
}

【讨论】:

  • 这完美解决了问题。非常感谢@Barmar
猜你喜欢
  • 2015-01-03
  • 2012-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-14
  • 1970-01-01
相关资源
最近更新 更多