这种C++方法可以简化吗?

Can this C++ method be simplified?

本文关键字:C++ 方法 这种      更新时间:2023-10-16

背景:

我一直在将间隙缓冲区算法实现为具有匹配自定义迭代器的 STL 容器。 Buffer 类在其他成员中有两个内部指针_gapStart_gapEnd,分别表示间隙的开始和结束。

BufferIterator有两个成员_buffer它是对它正在迭代的 Buffer 类的引用,_pos是缓冲区中的当前位置。 它与普通迭代器的不同之处在于,当它在缓冲区中前后移动时,它应该"跳过"间隙。

为此,我有下面的代码来实现operator+=(所有其他迭代器算术运算符都是根据它定义的)。这段代码有效,但我有一种唠叨的感觉,它可以变得更简单。

BufferIterator& operator+=(const difference_type& n) {
auto count = n;
if (count >= 0) {
while (count--) {
++_pos;
if (_pos == _buffer._gapStart) {
_pos += (_buffer._gapEnd - _buffer._gapStart);
}
}
} else {
while (count++) {
--_pos;
if (_pos == _buffer._gapEnd) {
_pos -= (_buffer._gapEnd - _buffer._gapStart);
}
}
}
return *this;
}

所以我想用下面的版本替换它。 但是它不起作用;它会导致段错误。 为什么? 在我看来,它应该是完全等效的,我不知道为什么不是。

BufferIterator& operator+=(const difference_type& n) {
if (n >= 0) {
_pos += n;
if (_pos >= b._gapStart) {
_pos += (b._gapEnd - b._gapStart);
}
} else {
_pos -= n;
if (_pos <= b._gapEnd) {
_pos -= (b._gapEnd - b._gapStart);
}
}
return *this;
}

谁能帮我理解这一点?是否有任何更简单的实现版本 1 的方法,或者它确实是实现它的最佳方法?

顺便说一句,如果它有助于在上下文中查看代码,我的简单编辑器可以在 Github 上找到。

第一个版本可以这样简化:

BufferIterator& operator+=(const difference_type& n) {
auto count = n;
if (count >= 0) {
while (count--) {
++_pos;
if (_pos == _buffer._gapStart) {
_pos = _buffer._gapEnd;
}
}
} else {
while (count++) {
--_pos;
if (_pos == _buffer._gapEnd) {
_pos = _buffer._gapStart;
}
}
}
return *this;
}

为了删除循环,您的代码可能如下所示:

BufferIterator& operator+=(const difference_type& n) {
if (n >= 0) {
if (_pos < b._gapStart && b._gapStart <= _pos + n) {
_pos += b._gapEnd - b._gapStart;
}
} else {
if (_pos + n <= b._gapEnd && b._gapEnd < _pos) {
_pos -= (b._gapEnd - b._gapStart);
}
}
_pos += n;
return *this;
}