C++ std::list size()has linear complexity

在sgi stl的实现版本中看到关于size member的实现。
size_type size() const {
    size_type __result = 0;
    distance(begin(), end(), __result);

    return __result;
  }
这里的distance是一个全局函数。
对于random_access iterator 而言是两个迭代器相减,具有O(1)的复杂度,而对于其他类型的迭代器则是++first到last的形式,具有O(n)的复杂度。

Why is list<>::size() linear time? 
The size() member function, for list and slist, takes time proportional to the number of elements in the list. This was a deliberate tradeoff. The only way to get a constant-time size() for linked lists would be to maintain an extra member variable containing the list's size. This would require taking extra time to update that variable (it would make splice() a linear time operation, for example), and it would also make the list larger. Many list algorithms don't require that extra word (algorithms that do require it might do better with vectors than with lists), and, when it is necessary to maintain an explicit size count, it's something that users can do themselves.

This choice is permitted by the C++ standard. The standard says that size() "should" be constant time, and "should" does not mean the same thing as "shall". This is the officially recommended ISO wording for saying that an implementation is supposed to do something unless there is a good reason not to.

One implication of linear time size(): you should never write

if (L.size() == 0) ...
Instead, you should write
if (L.empty()) ...
posted @ 2013-03-31 13:16  xuning2516  阅读(259)  评论(0编辑  收藏  举报