View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

C++ Standard Template Library (STL)

Updated on 30/01/2025570 Views

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!

What is STL in C++

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!

STL containers in C++

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.

Sequence Containers

These containers keep the sequence of elements and allow for sequential access. Here are the primary types:

Vector

  • Description: Vectors are similar to dynamic arrays, as their size can dynamically change. They offer random entry to elements and efficient insertions or deletions at the end.
  • Common Operations: push_back(), pop_back(), size(), at()

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

  • Description: A list is a data structure similar to an array, but it is implemented as a doubly linked list. This means that each element in the list contains not only its own value, but also references to the previous and next elements. Lists provide efficient insertion and deletion operations from anywhere within the container; however, they do not support random access of elements.
  • Common operations: push_back(), push_front(), pop_back(), pop_front()

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
  • Description: Deques are double-ended queues that allow insertion and deletion from both ends.
  • Common operations: push_back(), push_front(), pop_back(), pop_front()

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

Associative containers are designed to support fast search and retrieval operations based on keys.

Set

  • Description: Sets are collections of unique elements, stored in a sorted manner. They are typically implemented using red-black trees.
  • Common operations: insert(), erase(), find()

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

  • Description: Maps store key-value pairs sorted by keys. Each key can map to only one value.
  • Common operations: insert(), erase(), find()

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

Unordered containers are based on hash tables, allowing for faster average complexity for search, insert, and delete but do not maintain order among elements.

Unordered Set

  • Description: Unordered sets are collections of unique elements, organized using a hash table.
  • Common operations: insert(), erase(), find()

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

  • Description: Unordered maps store key-value pairs using a hash table. They allow fast access to elements using keys.
  • Common operations: insert(), erase(), find()

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.

STL concepts in C++

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

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:

  • Input iterators: Read and process values while moving forward.
  • Output iterators: Write values while moving forward.
  • Forward iterators: Navigate in one direction.
  • Bidirectional iterators: Navigate forward and backward (e.g., list and set).
  • Random access iterators: Directly access any element (e.g., vector and deque).

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

Algorithms

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:

  • Non-modifying: find(), count(), accumulate()
  • Modifying: sort(), reverse(), next_permutation()

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

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

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.

STL in C++ example programs

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.

C++ STL cheat sheet

Here's a quick cheat sheet I often use when working with STL:

  • Vector: Dynamic array.
    • Creation: std::vector<int> vec;
    • Access: vec[index];
    • Insert: vec.push_back(value);
    • Sort: std::sort(vec.begin(), vec.end());
  • Map: Key-value pairs, sorted by key.
    • Creation: std::map<std::string, int> m;
    • Access: m[key];
    • Insert: m[key] = value;
    • Find: m.find(key);
  • Set: Unique elements, sorted.
    • Creation: std::set<int> s;
    • Insert: s.insert(value);
    • Find: s.find(value);
  • Unordered Map: Key-value pairs, hashed by key.
    • Creation: std::unordered_map<std::string, int> um;
    • Access: um[key];
    • Insert: um[key] = value;
    • Find: um.find(key);

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!

Concluding Remarks

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.

FAQs

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.

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

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.