g++中STL容器的复杂度:其中容器为0 (n)

size() complexity of STL containers in G++: which containers are O(n)?

本文关键字:复杂度 STL g++      更新时间:2023-10-16

我想大多数人都明白size()函数的复杂度并不能保证是恒定的。尽管在某些实现中,它是常量。

c++编译器可能是最常用的编译器。那么,在g++的实现中,size()的复杂度是多少?如果它因容器的不同而不同,哪些容器具有线性复杂性?对于最常用的类型(如list、vector、deque、set、&Map),它们都是常数吗?

对于c++ 11,标准(23.2.1)指定对于所有容器在标准库的一致实现中(不幸的是,这并不意味着所有实现都是一致的;例如:GCC有这个问题)。

对于c++ 03,标准(23.1)说size "应该具有恒定的复杂性",事实证明(谢谢,评论者)这是一个强烈但不具约束力的建议;这意味着您必须阅读每个编译器提供的实现文档。

它可能会根据标准库的版本而变化。

对于GCC最近的版本(至少到4.6.2)List和基于List的CC_5不是常量时间,而是实现为{ return std::distance(begin(), end()); }

MSVC标准库跟踪大小的变化,只返回它的值(这使得splice() 0 (n),因为它必须在拼接时计数)。

From my /usr/include/c++/4.6.2/bits/stl_list.h:

/**  Returns the number of elements in the %list.  */
      size_type
      size() const
      { return std::distance(begin(), end()); }

vectorsetdequemap为常数时间。

这是std::deque

  size_type
  size() const
  { return this->_M_impl._M_finish - this->_M_impl._M_start; }

queuestack实际上是容器适配器,依赖于可以指定的底层容器。但是默认值是deque,这是一个常量。

, g++ 5.4.0文件/usr/include/c + +/5.4.0/位/stl_list.h

  /**  Returns the number of elements in the %list.  */
  size_type
  size() const _GLIBCXX_NOEXCEPT
  { return this->_M_node_count(); }

, g++ 4.8.5文件/usr/include/c + +/4.8.5/位/stl_list.h

  /**  Returns the number of elements in the %list.  */
  size_type
  size() const _GLIBCXX_NOEXCEPT
  { return std::distance(begin(), end()); }

所以它在4.8.5是线性的,在5.4.0是常数