如何在调用擦除C++后向上移动字符串向量的内容
How to shift contents of a string vector up after calling erase C++
我正在尝试实现一个撤消函数,用于为简单的文本编辑器程序插入新行。当我调用新行时,我递增字符串向量的行,并在其中插入一个空字符串。这会将新行下方的所有内容向下推 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。
相关文章:
- 通过字符串来计算长度需要更长的时间,而不是移动字符串几次?
- 尝试移动字符串中的每个位
- 为什么字符串流只读取整数中的第一个数字?如何使它只在空白处移动?
- 错误:移动文件时'QString'为非标量类型"std::__cxx11::字符串"
- 快速从文件中读取下一个字符串,而无需移动文件的位置
- 如何找到通过仅移动相邻字符创建的字符串的排列?-C++
- 通过单词列表将两个字符串移动以比较每个单词
- STD ::移动性能,同时将大字符串作为rvalue
- 如何在循环移动后从给定的字符串中找到一组不同的字符串
- 如何移动 std::ostringstream 的底层字符串对象?
- 从字符串和向量移动以不拥有任何堆内存
- 字符串将第一个单词移动到字符串的末尾
- 如何在不删除任何字符的情况下将字符从字符串中的某个位置移动到其最前面
- 需要从格式化字符串移动到二进制缓冲区
- C :在字符串#附录中移动语义
- 为什么包含std::字符串流的类的移动语义会导致编译器错误
- 是否建议将字符串std::移动到将被覆盖的容器中
- 试图编写能够从std::string中移动语义的字符串类
- 字符串移动构造函数是如何工作的
- 将字符串移动到矢量中