简体   繁体   中英

Is the complexity of vector::clear unspecified?

Per a discussion from Is `std::vector<primitive>::clear()` a constant time operation? , it was noted that the C++ standard does not appear to specify the running time of vector::clear .

It specifies the running time of list::clear (linear; §23.3.5.4.5), .clear for both ordered (table 102) and unordered associative containers (table 103) (both linear). However, vector::clear appears to be missing (though other vector members, like .data and .swap appear to have specified complexity).

Is it really unspecified, or did I miss something?

Is it really unspecified, or did I miss something?

Yes . At the moment, it is really unspecified.

There is an open library issue for this , whose text contains a link to a relevant Q&A on StackOverflow. The answer by Jonathan Wakely to that question clarifies what has been going on.

According to the linked proposal, the complexity requirement of clear() should be made linear for all sequence containers. However, one must keep in mind that complexity requirements are just upper bounds . Per Paragraph 17.5.1.4/7 of the C++11 Standard:

Complexity requirements specified in the library clauses are upper bounds, and implementations that provide better complexity guarantees satisfy the requirements.

This allows for possible optimizations, but does not mandate them.

Even when the linked proposal will be accepted, we will not be allowed to assume that clear() has O(1) complexity for sequence containers of non-class elements, even though this seems to be a natural and common optimization strategy (and the answer by dasblinkenlight to this question on SO confirms it).

Implementations will be allowed to adopt this strategy (per 17.5.1.4/7), but they won't be required to do so, because nowhere in the Standard such a constraint is (nor is it proposed to be) specified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM