Is the std::set iteration order always ascending according to the C++ specification?

前端 未结 5 827
遥遥无期
遥遥无期 2020-12-05 06:42

Here http://www.cplusplus.com/reference/stl/set/ I read that std::set in C++ is \"typically\" implemented as a tree (red-black one?) and it is sorted.

I could not un

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 07:05

    C++11 N3337 standard draft

    http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf

    23.2.4 "Associative containers" says:

    1 Associative containers provide fast retrieval of data based on keys. The library provides four basic kinds of associative containers: set, multiset, map and multimap.

    and:

    10 The fundamental property of iterators of associative containers is that they iterate through the containers in the non-descending order of keys where non-descending is defined by the comparison that was used to construct them.

    so yes, order is guaranteed by the C++ standard.

    This is why gcc 6.4.0 for example implements it as a BST instead of hashmap: What is the underlying data structure of a STL set in C++?

    Contrast this with C++11 unordered_set, which tends to provide better performance with a hashmap implementation, at the cost of being more restricted (no free sorted traversal) as shown at:

    • What is the underlying data structure of a STL set in C++?
    • Why would anyone use set instead of unordered_set? e.g. using a hash set.

提交回复
热议问题