1] Explain the concept of the Standard Template Library (STL) in C++.
What are its
key components?
The Standard Template Library (STL) is a powerful set of C++ template classes
designed to provide general-purpose classes and functions with templates that
implement many popular and commonly used algorithms and data structures like
vectors, lists, and stacks. It is a significant part of the C++ Standard Library.
Key Components of STL
STL is divided into four main components:
1. Containers:
o Containers store collections of objects. The most commonly used
containers in STL are:
▪ Sequence Containers: Allow the storage of elements in a
specific order.
▪ Examples: vector, deque, list
▪ Associative Containers: Allow the storage of elements in a
sorted order (by default).
▪ Examples: set, multiset, map, multimap
▪ Unordered Containers: Store elements in an unordered
manner and allow fast access to elements.
▪ Examples: unordered_set, unordered_map
2. Algorithms:
o Algorithms perform operations on the elements of containers. They are
used to perform various tasks, such as searching, sorting, counting,
manipulating, etc.
o Examples: sort, find, for_each, binary_search, accumulate
3. Iterators:
o Iterators are objects that point to an element in a container and are
used to traverse through the elements of the container.
o They act like pointers and are crucial for performing operations on
container elements.
o Examples: begin, end, rbegin, rend
4. Functors (Function Objects):
o Functors are objects that can be treated as though they are a function
or function pointer.
o They are used with STL algorithms to customize behavior.
o Example: std::less, std::greater, user-defined functors
2] Write a program to implement map in STL
#include <iostream>
#include <map>
using namespace std;
int main() {
// Create a map of string keys and int values
map<string, int> myMap;
// Insert elements into the map
myMap["Alice"] = 25;
myMap["Bob"] = 30;
myMap["Charlie"] = 35;
// Iterate and display the map elements
for (const auto& entry : myMap) {
cout << [Link] << ": " << [Link] << endl;
}
return 0;
}
Alice: 25
Bob: 30
Charlie: 35
Explanation:
1. Creating a Map:
o map<string, int> myMap;: Declares a map with string keys and int
values.
2. Inserting Elements:
o myMap["Alice"] = 25;: Inserts a key-value pair ("Alice", 25).
3. Iterating and Displaying Elements:
o for (const auto& entry : myMap): Iterates through the map and prints
each key-value pair.
4. Finding and Displaying an Element:
o auto it = [Link](key);: Finds an element by key.
o Checks if the key exists in the map and prints the corresponding value.