For working professionals
For fresh graduates
More
4. C++ Variable
10. C++ for Loop
12. C++ Lambda
13. Loop in C++
15. Array in C++
16. Strings in C++
17. Substring in C++
29. Vector in C++
30. Map in C++
31. Pair in C++
33. Iterators in C++
34. Queue in C++
36. Stack in C++
37. ifstream in C++
40. Templates in C++
43. Namespace in C++
46. Recursion in C++
48. C++ Shell
49. Setw in C++
51. Atoi in C++
54. C# vs C++
55. C++ GUI
56. C++ Game Code
57. Class in C++
58. C++ Header Files
63. Cin in C++
64. Printf in C++
65. Struct in C++
66. C++ List
68. C++ Comments
72. Sorting in C++
STL in C++ is a strong set of C++ classes to offer general-purpose processes and functions in a templated manner. The idea is to give you easy access to carrying out various famous algorithms and data structures like vectors, lists, queues as well as stacks.
I have deep experience using this STL in my job as a software engineer and also in the teaching field. In this tutorial, let me take this opportunity to walk you through the fundamentals of STL in C++ including STL in C++ example programs, STL libraries C++, and even a C++ STL cheat sheet at the end of the tutorial! So, read till the end!
STL, short for Standard Template Library, is a crucial portion of C++ computer programming language. It provides an extensive assortment of methods, functions and algorithms to manage data structures. When I was introduced to STL in C++, it really surprised me how much it made my code easier and saved time from repetitive work. STL isn't only about containers plus algorithms but also improving your code's efficiency, readability and maintainability too!
Within the STL in C++, containers are considered as one of the most basic parts. Containers are objects which hold data, and there exist various types of containers in the STL, each having its own distinct characteristics for organizing and accessing specific kinds of data. Let me provide you with a short summary on every type along with some examples and code pieces to demonstrate how they can be utilized.
These containers keep the sequence of elements and allow for sequential access. Here are the primary types:
Here’s an example of using vector STL containers in C++:
Example:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec;
vec.push_back(10);
vec.push_back(20);
vec.push_back(30);
// Access and print elements
std::cout << "Vector: ";
for (int i : vec) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
Output:
Vector : 10 20 30
List
Here’s how you can use list STL container in C++:
Example:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec;
vec.push_back(10);
vec.push_back(20);
vec.push_back(30);
// Access and print elements
std::cout << "Vector: ";
for (int i : vec) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
Output:Deque
Vector : 10 20 30
Example:
#include <iostream>
#include <deque>
int main() {
std::deque<int> dq;
dq.push_front(10);
dq.push_back(20);
dq.push_front(30);
// Iterate and print elements
std::cout << "Deque: ";
for (int i : dq) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
Output:
Deque : 30 10 20
Associative containers are designed to support fast search and retrieval operations based on keys.
Example:
#include <iostream>
#include <set>
int main() {
std::set<int> s;
s.insert(10);
s.insert(20);
s.insert(10); // Duplicate, won't be inserted
// Iterate and print elements
std::cout << "Set: ";
for (int i : s) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
Output:
Set : 10 20
Map
Example:
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> m;
m["apple"] = 10;
m["banana"] = 20;
m["orange"] = 30;
// Iterate and print elements
std::cout << "Map: ";
for (const auto& pair : m) {
std::cout << "{" << pair.first << ", " << pair.second << "} ";
}
std::cout << std::endl;
return 0;
}
Output:
Map: {apple, 10} {banana,20} {orange,30}
Unordered containers are based on hash tables, allowing for faster average complexity for search, insert, and delete but do not maintain order among elements.
Example:
#include <iostream>
#include <unordered_set>
int main() {
std::unordered_set<int> us;
us.insert(10);
us.insert(20);
us.insert(10); // Duplicate, won't be inserted
// Iterate and print elements
std::cout << "Unordered Set: ";
for (int i : us) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
Output:
Unordered Set: 20 10
Unordered Map
Example:
#include <iostream>
#include <unordered_map>
#include <string>
int main() {
std::unordered_map<std::string, int> um;
um["apple"] = 10;
um["banana"] = 20;
um["orange"] = 30;
// Iterate and print elements
std::cout << "Unordered Map: ";
for (const auto& pair : um) {
std::cout << "{" << pair.first << ", " << pair.second << "} ";
}
std::cout << std::endl;
return 0;
}
Output:
Unordered Map: {orange,30} {banana, 20} {apple,10}
Through these containers, I can select the suitable data structure as per requirement of my task to make sure that my C++ applications are efficient and strong. The STL containers provide a flexible collection of utilities which can manage nearly every kind of data organization one may require in their programs.
The Standard Template Library (STL) is constructed based on a handful of fundamental ideas, which provide it with adaptability and strength. When programmers grasp these notions, they can efficiently employ STL's characteristics to make fast and beautiful C++ applications. Now let's dive into a more detailed view of certain important STL concepts:
Iterators are perhaps the most crucial concept within the STL. They act like pointers and provide a means to access the elements of a container sequentially without exposing the underlying structure of the data. Iterators abstract the container type, allowing the same algorithm to work across any container that provides appropriate iterators.
Iterators are of the following types:
Example:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {4, 1, 3, 5, 2};
std::sort(vec.begin(), vec.end()); // Using iterators for sorting
// Use iterator to access and print elements
std::cout << "Sorted Vector: ";
for (auto it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
Output:
Sorted Vector: 1 2 3 4 5
STL provides a vast library of algorithms to perform operations such as searching, sorting, counting, manipulating, and others on containers. The beauty of STL algorithms lies in their ability to operate through iterators, making them independent of the container type.
Some of the examples of algorithms include:
Example:
#include <algorithm>
#include <array>
#include <iostream>
int main() {
std::array<int, 5> arr = {1, 2, 3, 4, 5};
// Reverse the array using std::reverse
std::reverse(arr.begin(), arr.end());
std::cout << "Reversed Array: ";
for (int num : arr) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
Output:
Reserved Array: 5 4 3 2 1
Functors (or function objects) are objects that can be called as if they were ordinary functions. This includes objects of a class that have implemented the operator(). Functors are particularly useful because they can maintain state and can be customized more easily than functions.
Here’s how you can use a functor:
Example:
#include <iostream>
#include <algorithm>
#include <vector>
class Increment {
private:
int num;
public:
Increment(int n) : num(n) {}
int operator () (int arr_num) const {
return num + arr_num;
}
};
int main() {
std::vector<int> vect = {1, 2, 3, 4, 5};
std::transform(vect.begin(), vect.end(), vect.begin(), Increment(5));
std::cout << "Vector after incrementing by 5: ";
for (int i : vect) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
Output:
Vector after incrementing by 5: 6 7 8 9 10
Adaptors modify a container to provide a different interface. For instance, stack and queue are implemented as container adaptors, which internally use deque but provide a restricted interface to fit specific needs.
Let's look at a simple example to see how STL is used in C++:
Example:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// Create a vector of integers
std::vector<int> vec = {4, 1, 3, 5, 2};
// Sort the vector
std::sort(vec.begin(), vec.end());
// Print the sorted vector
for (int i : vec) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
Output:
1 2 3 4 5
In this program, I've used a vector to store integers and the sort algorithm from STL to sort the vector. This example demonstrates the simplicity and power of STL in handling data structures and algorithms.
Here's a quick cheat sheet I often use when working with STL:
This cheat sheet serves as a quick guide for the frequently used STL containers and functions. For those who wish to explore further into the realm of STL in C++, there are many courses available from upGrad in computer engineering and software development!
The STL in C++ is a basic but powerful way to make your programming work better. It offers clear and strong algorithms, containers, iterators, and functors that can lessen the difficulty of your code greatly while boosting its performance. When you use STL, you are not just making your code more efficient but also more expressive and easier to comprehend and manage.
For people who want to learn more about STL or enhance their C++ abilities, they can explore courses at upGrad.
1. What is STL in C++?
The library STL in C++ gives templated classes and functions to work with data structures and algorithms.
2. What are the main components of STL?
The main components of STL are containers, algorithms, iterators, and functors.
3. How do I include STL in my C++ code?
Include the necessary headers like <vector>, <algorithm>, <map>, etc., based on what components you need.
4. What are containers in STL?
Containers are like data structures that can keep data. They have many types, such as vectors, lists, deques, sets and maps.
5. What are iterators in STL?
Iterators are like a sign pointing to elements within a container, and they can be utilized to go through the container.
6. Can I use custom data types with STL containers?
Certainly, it is possible to employ custom data types with STL containers. This can be accomplished by defining operators such as ==, <, etc., or by giving your own hash functions for unordered containers.
7. Are STL containers thread-safe?
No, STL containers do not have built-in thread safety. It is necessary to use mutexes or other synchronization methods for ensuring thread safety while accessing STL containers from many threads.
8. How is STL different from the C++ Standard Library?
STL, which stands for Standard Template Library, is essentially a section of the C++ Standard Library. It particularly deals with containers, algorithms, iterators and functors. The C++ Standard Library is a collection of useful features such as I/O operations, threading support and more.
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.