这种C++方法可以简化吗?
Can this C++ method be simplified?
背景:
我一直在将间隙缓冲区算法实现为具有匹配自定义迭代器的 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;
}
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 没有为自己的结构调用列表推回方法
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- 枚举环境变量的惯用C++14/C++17方法
- 初始化具有非默认构造函数的std::数组项的更好方法