C++ 标准规定的具有时间复杂度的操作能否动态分配内存?
Can operations with a time complexity mandated by the C++ standard dynamically allocate memory?
C++ 标准不强制要求内存分配的时间复杂度,因为这超出了它的范围(通常取决于 OS 的行为),但这是否意味着任何具有指定复杂度的东西都不能动态分配内存?
例如,标准库中的大多数容器都需要具有恒定时间复杂度的默认构造函数,因此任何抢先动态分配内存的实现都将违反标准。 (该特定行为是否合乎需要无关紧要——这只是一个听起来有点合理的例子。)对吗?
该标准明确规定了 "time complexity" 它强制要求的内容:
23.2.1[container.requirements.general]/2
All of the complexity requirements in this Clause are stated solely in terms of the number of operations on the contained objects. [ Example: the copy constructor of type vector <vector<int> >
has linear complexity, even though the complexity of copying each contained vector<int>
is itself linear. — end example ]
对于该条款之外的功能,复杂性要求已明确说明,例如
25.4.3.1[lower.bound]/3
(即std::lower_bound
)
Complexity: At most log2(last - first) + O(1)
comparisons.
(注意只计算比较:lower_bound 可以,并且对于前向迭代器,将执行线性扫描)
所以是的,标准要求其复杂性的算法可以动态分配内存,或者做任何他们想做的事情,只要它们满足实际约束。
C++ 标准不强制要求内存分配的时间复杂度,因为这超出了它的范围(通常取决于 OS 的行为),但这是否意味着任何具有指定复杂度的东西都不能动态分配内存?
例如,标准库中的大多数容器都需要具有恒定时间复杂度的默认构造函数,因此任何抢先动态分配内存的实现都将违反标准。 (该特定行为是否合乎需要无关紧要——这只是一个听起来有点合理的例子。)对吗?
该标准明确规定了 "time complexity" 它强制要求的内容:
23.2.1[container.requirements.general]/2
All of the complexity requirements in this Clause are stated solely in terms of the number of operations on the contained objects. [ Example: the copy constructor of type
vector <vector<int> >
has linear complexity, even though the complexity of copying each containedvector<int>
is itself linear. — end example ]
对于该条款之外的功能,复杂性要求已明确说明,例如
25.4.3.1[lower.bound]/3
(即std::lower_bound
)
Complexity: At most
log2(last - first) + O(1)
comparisons.
(注意只计算比较:lower_bound 可以,并且对于前向迭代器,将执行线性扫描)
所以是的,标准要求其复杂性的算法可以动态分配内存,或者做任何他们想做的事情,只要它们满足实际约束。