This page is a snapshot from the LWG issues list, see the Library Active Issues List for more information and the meaning of NAD status.

632. Time complexity of size() for std::set

Section: 24.2 [container.requirements] Status: NAD Submitter: Lionel B Opened: 2007-02-01 Last modified: 2016-01-28

Priority: Not Prioritized

View all other issues in [container.requirements].

View all issues with NAD status.

Discussion:

A recent news group discussion:

Anyone know if the Standard has anything to say about the time complexity of size() for std::set? I need to access a set's size (not to know if it is empty!) heavily during an algorithm and was thus wondering whether I'd be better off tracking the size "manually" or whether that'd be pointless.

That would be pointless. size() is O(1).

Nit: the standard says "should" have constant time. Implementations may take license to do worse. I know that some do this for std::list<> as a part of some trade-off with other operation.

I was aware of that, hence my reluctance to use size() for std::set.

However, this reason would not apply to std::set<> as far as I can see.

Ok, I guess the only option is to try it and see...

If I have any recommendation to the C++ Standards Committee it is that implementations must (not "should"!) document clearly[1], where known, the time complexity of *all* container access operations.

[1] In my case (gcc 4.1.1) I can't swear that the time complexity of size() for std::set is not documented... but if it is it's certainly well hidden away.

[ Kona (2007): This issue affects all the containers. We'd love to see a paper dealing with the broad issue. We think that the complexity of the size() member of every container -- except possibly list -- should be O(1). Alan has volunteered to provide wording. ]

[ Bellevue: ]

Mandating O(1) size will not fly, too many implementations would be invalidated. Alan to provide wording that toughens wording, but that does not absolutely mandate O(1).

[ Batavia (2009-05): ]

We observed that the wording "should" (in note a) has no effect. Howard prefers that O(1) size be mandated. It is not clear that this issue can be resolved to everyone's satisfaction, but Alan will provide wording nonetheless.

[ 2009-07 Frankfurt ]

Fixed by paper N2923.

Proposed resolution: