Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ STL list vs set

Tags:

Which of those two is faster for random insertions and deletions?

My guess is list.

Though having the values as the keys as in the case of sets is attractive too.

Is performance similar for iterating over the whole container?

like image 665
user240137 Avatar asked Feb 20 '10 15:02

user240137


People also ask

What is difference between set and Unordered_set?

Set is an ordered sequence of unique keys whereas unordered_set is a set in which key can be stored in any order, so unordered. Set is implemented as a balanced tree structure that is why it is possible to maintain order between the elements (by specific tree traversal).

Is set faster than vector?

Vector is faster for insertion and deletion of elements at the end of the container. Set is faster for insertion and deletion of elements at the middle of the container.

What are sets in STL?

Sets are the containers in C++ STL for storing elements in a given order. The elements of a set must be unique.


2 Answers

List

  1. Searching (linear time).
  2. Inserting, deleting, moving (takes constant time).
  3. Elements may be ordered.
  4. Elements may be sorted.
  5. Elements may be duplicate.

Set

  1. Searching (logarithmic in size).
  2. Insert and delete (logarithimic in general).
  3. Elements are un-ordered.
  4. Elements are always sorted from lower to higher.
  5. Elements are unique.
like image 70
cpx Avatar answered Oct 15 '22 18:10

cpx


std::list is O(1) for inserts and deletions. But you may well need O(n) to find the insertion or deletion point. std::set is O(log(n)) for inserts and deletions, it is usually implemented as a red-black tree.

Consider the effort to find the insert/delete point to make your choice.

like image 37
Hans Passant Avatar answered Oct 15 '22 20:10

Hans Passant