What is the underlying data structure of a STL set in C++?

后端 未结 7 928
自闭症患者
自闭症患者 2020-11-29 01:11

I would like to know how a set is implemented in C++. If I were to implement my own set container without using the STL provided container, what would be the best way to go

7条回答
  •  臣服心动
    2020-11-29 01:31

    I understand STL sets are based on the abstract data structure of a binary search tree. So what is the underlying data structure? An array?

    As others have pointed out, it varies. A set is commonly implemented as a tree (red-black tree, balanced tree, etc.) though but there may be other implementations that exist.

    Also, how does insert() work for a set?

    It depends on the underlying implementation of your set. If it is implemented as a binary tree, Wikipedia has a sample recursive implementation for the insert() function. You may want to check it out.

    How does the set check whether an element already exists in it?

    If it is implemented as a tree, then it traverses the tree and check each element. However, sets do not allow duplicate elements to be stored though. If you want a set that allows duplicate elements, then you need a multiset.

    I read on wikipedia that another way to implement a set is with a hash table. How would this work?

    You may be referring to a hash_set, where the set is implemented using hash tables. You'll need to provide a hash function to know which location to store your element. This implementation is ideal when you want to be able to search for an element quickly. However, if it is important for your elements to be stored in particular order, then the tree implementation is more appropriate since you can traverse it preorder, inorder or postorder.

提交回复
热议问题