GCC 列表节点交换实现过于复杂
gcc list node swap implementation overcomplicated?
我正在使用 SGI STL (GCC) 作为自定义库的参考,在深入研究std::list::swap()
时遇到了以下实现,
注意:此方法不能正确处理相邻节点。
// namespace std {
// namespace __detail {
void
_List_node_base::swap(_List_node_base& __x, _List_node_base& __y) throw()
{
if ( __x._M_next != &__x )
{
if ( __y._M_next != &__y )
{
// Both __x and __y are not empty.
std::swap(__x._M_next,__y._M_next);
std::swap(__x._M_prev,__y._M_prev);
__x._M_next->_M_prev = __x._M_prev->_M_next = &__x;
__y._M_next->_M_prev = __y._M_prev->_M_next = &__y;
}
else
{
// __x is not empty, __y is empty.
__y._M_next = __x._M_next;
__y._M_prev = __x._M_prev;
__y._M_next->_M_prev = __y._M_prev->_M_next = &__y;
__x._M_next = __x._M_prev = &__x;
}
}
else if ( __y._M_next != &__y )
{
// __x is empty, __y is not empty.
__x._M_next = __y._M_next;
__x._M_prev = __y._M_prev;
__x._M_next->_M_prev = __x._M_prev->_M_next = &__x;
__y._M_next = __y._M_prev = &__y;
}
}
在我看来,这似乎可以简化为,
void
_List_node_base::swap(_List_node_base& __x, _List_node_base& __y) throw()
{
_List_node_base* __xnext = __x._M_next;
_List_node_base* __xprev = __x._M_prev;
_List_node_base* __ynext = __y._M_next;
_List_node_base* __yprev = __y._M_prev;
__xnext->_M_prev = __xprev->_M_next = &__y;
__ynext->_M_prev = __yprev->_M_next = &__x;
std::swap(__x._M_next,__y._M_next);
std::swap(__x._M_prev,__y._M_prev);
}
我已经对所有情况(空/空、空/非空等)进行了测试,包括引用同一节点的__x
和__y
,它似乎有效,但是,我对 SGI 代码库的信任让我怀疑自己。
所以我的问题是:这是正确的吗?如果是这样,使用较长的版本有什么好处吗?
谢谢。
自我作业检查风靡一时。众所周知,他们现在很悲观和隐藏错误。你可能想找到一个更现代的灵感来源。
相关文章:
- 函数复杂度分析
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- while循环中while循环的时间复杂度是多少
- 我可以创建一个包含两个变量的 for 循环,但时间复杂度仍然为 O(n) 吗?
- 函数的时间复杂度是多少?
- 如何检查两个 std::向量在小于 O(n) 的时间复杂度内是否相等
- 使用 Python Extension API 包装复杂C++类
- 时间复杂度 当具有复合数据类型(如元组或对)时?
- 如何计算此排序函数的时间复杂度?
- 计算两个代码块的时间复杂度
- 将平面阵列重塑为复杂的特征类型
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- 当 A 在 for 循环中调用函数 B 时,如何计算函数 A 的空间复杂度?
- 如何在复杂继承中访问静态成员变量
- C++ 中具有 O(1) 搜索时间复杂度的数据结构
- OpenCV 傅里叶变换复杂输出问题
- 具有嵌套 if-else 的循环的时间复杂度
- 在<short> <double> C++ 中static_cast复杂到复杂
- 复杂而复杂的模板
- 我可以使用' == '来比较两个向量吗?我试过了,似乎工作正常。但我不知道它是否适用于更复杂的情况