g++中STL容器的复杂度:其中容器为0 (n)
size() complexity of STL containers in G++: which containers are O(n)?
我想大多数人都明白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()); }
vector
、set
、deque
、map
为常数时间。
这是std::deque
的
size_type
size() const
{ return this->_M_impl._M_finish - this->_M_impl._M_start; }
queue
和stack
实际上是容器适配器,依赖于可以指定的底层容器。但是默认值是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是常数
- 函数复杂度分析
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- while循环中while循环的时间复杂度是多少
- 我可以创建一个包含两个变量的 for 循环,但时间复杂度仍然为 O(n) 吗?
- 函数的时间复杂度是多少?
- 如何检查两个 std::向量在小于 O(n) 的时间复杂度内是否相等
- 时间复杂度 当具有复合数据类型(如元组或对)时?
- 如何计算此排序函数的时间复杂度?
- 计算两个代码块的时间复杂度
- 当 A 在 for 循环中调用函数 B 时,如何计算函数 A 的空间复杂度?
- C++ 中具有 O(1) 搜索时间复杂度的数据结构
- 具有嵌套 if-else 的循环的时间复杂度
- C++中 std::map 的运行时复杂度是多少?
- 将树节点添加到向量向量中的 n 元树遍历的平均和最坏情况时间复杂度是多少?
- 如何计算函数的时间复杂度?
- 将字符串插入到c++stl集的时间复杂度
- 用stl向量计算复杂度
- g++中STL容器的复杂度:其中容器为0 (n)
- C++:使用 STL 排序对不同列上的整数 2d 数组进行排序的时间复杂度
- 是STL size()在恒定复杂度或线性上运行