如何在调用擦除C++后向上移动字符串向量的内容

How to shift contents of a string vector up after calling erase C++

本文关键字:字符串 移动 向量 调用 擦除 C++      更新时间:2023-10-16

我正在尝试实现一个撤消函数,用于为简单的文本编辑器程序插入新行。当我调用新行时,我递增字符串向量的行,并在其中插入一个空字符串。这会将新行下方的所有内容向下推 1。它看起来像这样(其中 | 是光标):

Before
1: Hello
2: |World
After inserting a new line between hello and world
1: Hello
2: 
3: |World

当我调用我的撤消函数时,我希望它删除该行(在本例中为空行),然后将每一行向上推一行。我知道insert()处理移动元素,但是erase()有某种等效物吗?这是我的insertNewLine()代码

void Editor::insertNewLine()
{
    std::string currLine = lines[row];
    size_t tempSize = currLine.size();
    int lengthOffset = getSubstringOffset(tempSize, column);
    std::string cutTemp = currLine.substr(column, lengthOffset);
    // Insert a new line
    lines[row].erase(column);
    // after incrementing, row and amount of lines, initialize the new row
    numberOfLines++;
    lines.insert(lines.begin() + row, ""); // initialize and shift other rows
    row++;
    column = 1;
    lines[row] += cutTemp; // insert substring into new line
}

如果我在我要撤消的事情下面没有任何行,我尝试撤消此操作。这是我当前的撤消代码:

void Editor::undoNewLine()
{
    size_t updateCol = lines[row - 1].size(); // holds size of our old string
    lines[row - 1] += lines[row];
    lines[row].erase(column);
    row--;
    numberOfLines--;
    column = updateCol; // update to point back to where we were
}

当我擦除下面有行的内容时,它看起来像这样:

Before (we insert new lines, and end up creating a new line after row 1, which we want to undo)
1. Hello
2. |
3. asdf
4. rld
After user hits undo key
1. |Hello
2. 
3. asdf

不过,它应该是这样的:

Before
1. Hello
2. |
3. asdf
4. rld
After
1. |Hello
2. asdf
3. rld

那么我怎样才能擦除一个元素并让它像insert()一样将所有内容向上移动一行呢?

您应该删除该行,而不是在字符串中删除:

void Editor::undoNewLine()
{
    size_t updateCol = lines[row - 1].size(); // holds size of our old string
    lines[row - 1] += lines[row];
    lines.erase(lines.begin() + row);
    row--;
    numberOfLines--;
    column = updateCol; // update to point back to where we were
}

第三行是lines[row].erase(column);谁 - 据我所知 - 在你的字符串中擦除。

顺便说一句,您应该避免使用numberOfLines,因为它需要准确反映lines.size(),我认为,如果您使用lines.size(),错误将是显而易见的,它仍然是 4。