![]() |
VOOZH | about |
In C++, the Standard Template Library (STL) provides ready-made tools for handling data structures and algorithms efficiently. Built on templates, STL works with any data type and includes four main parts: containers, algorithms, iterators, and function objects.
Below are some of the most important interview questions about STL.
STL stands for Standard Template Library. It provides four main components:
The major differences between the arrays and lists are:
Arrays | Lists |
|---|---|
| Array are contiguous memory, has fixed size, allows O(1) random access, efficient memory use. | Lists are classic individual elements that are linked or connected to each other with the help of pointers and do not have a fixed size. |
| Arrays are static in nature. | Lists are dynamic in nature |
| Uses less memory than linked lists. | Uses more memory as it has to store the value and the pointer memory location |
STL containers are predefined data structures in C++ that store collections of data in various ways. They are categorized into three types:
1. Sequence Containers: Maintain the order of insertion.
Example:
vector<int> v = {1, 2, 3};
2. Associative Containers: Store elements using keys (ordered).
Example:
map<string, int> age;
age["Alice"] = 25;
3. Unordered Associative Containers: Use hash tables instead of trees.
Example:
unordered_map<string, int> scores;
4. Container Adapters: Built on other containers with restricted interface
Containers save time and effort by providing built-in operations like insertion, deletion, and search with optimal complexity.
The vector container in C++ STL is a dynamic array that can grow or shrink in size at runtime. It provides random access to elements and stores them in contiguous memory locations, like traditional arrays.
Implementation Details:
Features:
Limitations:
Example:
The vector is one of the most commonly used STL containers due to its efficiency, flexibility, and support for standard operations.
If you **modify a std::vector while iterating through it using a range-based for loop, the behavior can be unpredictable and often unsafe. Here's why:
Wrong Usage:
Correct Approach (Using Index):
One assume the range-based loop reflects vector changes, but it doesn’t, it can crash or skip elements
An iterator is an object (like a pointer) used to traverse containers. STL uses iterators to access elements in a uniform manner, regardless of the container. Iterators help in writing generic algorithms that work across different container types.
Types of Iterators:
| Type | Description |
|---|---|
| Input Iterator | Read-only access, single pass |
| Output Iterator | Write-only access, single pass |
| Forward Iterator | Read/write, multiple passes |
| Bidirectional | Traverse both directions |
| Random Access | Direct jump to any position (e.g., vector) |
Example:
10 20 30
Modifying a container (like inserting or erasing elements) while iterating over it can lead to undefined behavior because iterators can become invalidated.
To safely erase elements during iteration, we must:
Example Code:
1 2 4 5 6
remove() shifts all non-3s forward and returns a new end iterator. erase() then removes the trailing garbage efficiently.
How are they used?
Example:
98 65 45 34 3 2
Function objects:
They provide flexibility in customizing STL operations like sorting or filtering.
Lambda expressions are anonymous functions defined inline using the [] syntax. They are commonly used with STL algorithms to simplify code.
[ capture ] (parameters) -> return_type { body }
Example:
2
Advantages:
Lambdas improve clarity and reduce boilerplate in functional-style C++ code.
Allocators define how memory is allocated and deallocated for STL containers. By default, containers use std::allocator<T> which uses new/delete. Custom allocators can be provided for special needs such as memory pools, shared memory, or tracking.
Custom Allocator Example:
Use Cases:
Feature | map | unordered_map | multimap |
|---|---|---|---|
Ordering | Ordered by keys (ascending by default) | No ordering (hash table based) | Ordered by keys (allows duplicates) |
Underlying structure | Red-Black Tree (Balanced BST) | Hash Table | Red-Black Tree (like map) |
Key Uniqueness | Keys are unique | Keys are unique | Allows duplicate keys |
Search Time | O(log n) search time | Average O(1), worst O(n) | O(log n) search time |
Insertion Time | O(log n) insertion time | Average O(1), worst O(n) | O(log n) insertion time |
Duplicates Allowed | No duplicates allowed | No duplicates allowed | Duplicates allowed |
Header File | <map> header file | <unordered_map> header file | <map> header file |
Use Case | Use when sorted keys are needed | Use for fast access without ordering | Use when multiple values per key are needed |
Example:
map<int, string> m;
unordered_map<int, string> um;
multimap<int, string> mm;
Choosing the right container depends on whether order, speed, or duplicate keys are required.
Set and map do not allow duplicate keys. The insert() method returns a pair<iterator, bool>, where bool indicates success.
Example:
Inserted Duplicate
One often assume insert() silently overwrites in set, but it doesn’t. Checking return value is key.
insert | emplace |
|---|---|
| Constructs the object before insertion | Constructs the object in-place inside the container |
| Requires a fully constructed object as an argument | Accepts constructor arguments directly |
| May involve copy or move operations | Avoids unnecessary copy/move; more efficient |
Example:
Constructed with 5 Constructed with 10
emplace() can significantly improve performance in complex objects or in associative containers like map.
Remove-Erase Idiom:
v.erase(std::remove(v.begin(), v.end(), value), v.end());
std::remove to shift undesired elements, then erase() to remove them and resize the vector.Example:
1 3 4
Beginners expect remove() to delete from the container, but STL separates algorithm logic (remove) from container mutation (erase).
To sort a vector<pair<int, int>> by the second element of the pairs using STL, you can use std::sort with a custom comparator.
Example:
3 : 2 2 : 3 1 : 4
STL sort by default sorts by .first for pairs.
Using a std::vector as a key in an unordered_map is not allowed by default because:
To use std::vector as a key in unordered_map, you must provide:
Fix with Custom Hasher:
10
Note: Most STL types like vector work in map, but not in unordered_map unless hash function is provided.