Sequence vs Associative containers in C++
In standard template library they refer to the group of container class template, we use to them store data. One common property as the name suggests is that elements can be accessed sequentially.
Each of the following containers use different algorithm for data storage thus for different operations they have different speed. And all the elements in the containers should be of same type.
- array = It implements non-resizable array.
ex: int arr; // array of fixed size 10.
- vector = It implements dynamic array with faster random access, these are quite useful as unlike arrays they can resize.
ex: vector<int> v; // vector of int type
- dequeue It is used to implement double-ended queue with faster random access
ex: dequeue dq; //dequeue of character type
- forward_list : It implements singly linked list.
ex: forward_list fl; // forward_list of int type.
- list : It implements double linked list.
ex: list l; // lists of int
In standard template libraries, they refer to the group of class templates used to implement associative arrays. They are used to store elements but have some constraints placed on their elements.
And two important characteristics of these containers are
- There exists a key. In case of map and set, key is unique. In case of multimap and multiset, multiple values for a key are allowed. In case of map and multimap, there are key-value pairs. In case of set, there are only keys.
- Elements follow strict weak ordering..
These are the following which comes under the associative containers
- map: here each key we create must be unique.
ex: map geek_no; // Here first data type is key and second data type is value
- set: here also key we create must be unique but one important distinction from map is that here the value itself acts as a key so it means that elements in set are unique i.e. no repetition.
ex: set s; // value itself acts as a key.
- multimap: same as map but here key need not to be unique.
ex: multimap geeks_no;
- multiset: same as set but here uniqueness of elements doesn’t matter i.e. we can have same element multiple time unlike set.
ex: multiset marks;
Sequence vs associative (complexity wise)
In sequence containers
- Simple insertion takes constant time.
- Front has constant amortized time.
- Insertion in the middle is quite slow.
In associative containers, most complexities are in logarithmic terms
- Inserting an element is O(log n)
- Removing an element O(log n)
- Searching for an element O(log n)
- Incrementing or decrementing iterator O(1)(amortized)
- Insertion in middle is faster.
Unordered Associative Container
Note that every associative container has unordered associative container which contains elements without any specific order. Examples of unordered associative containers are unordered_set, unordered_map, unordered_multimap, unordered_multiset.