Looking For Anything Specific?

A Beginner's Guide to the Standard Template Library in C++

C++ is one of the most powerful and intimidating programming languages that you might encounter as a beginner. The reason is pretty straightforward. It demands a lot of code to achieve the desired output. The standard template library, or STL, can help you solve this conundrum.

Considering the amount of time and effort consumed while writing code for functions like sorting and searching, STL can help you perform all these operations with just a single line of code. This library can be immensely useful for problem-solving and technical interview preparation.

What Is the Standard Template Library?

The Standard Template Library, or STL, is a C++ library that consists of prebuilt functions and containers. It includes some prominent template classes for common data structures like vectors, stacks, queues, and some handy algorithmic functions like binary search to make programming easier.

The Standard Template Library in C++ consists of four components:

  1. Algorithms
  2. Containers
  3. Functions
  4. Iterators

Let's take a look at the algorithms and containers in greater depth, as those are the most commonly used components of the STL.

Algorithms in STL

The <algorithm> header file is a part of the STL that consists of several algorithmic functions that can be used instead of manually coding them. Some of the algorithms included are binary search, sorting, and reverse, which are extremely useful.

To begin with, you need to import the <algorithm> header in your C++ file. The syntax is as follows:

#include <algorithm>

For the upcoming methods, consider an array variable with the values of {6, 2, 9, 1, 4} as an example.

int arr[] = {6, 2, 9, 1, 4};

sort()

The sort() function helps you sort all the elements inside the specified data structure in ascending order. This function takes two parameters: the starting iterator and the ending iterator.

Related: An Introduction to the Merge Sort Algorithm

Syntax:

sort(start_iterator, end_iterator);

Here's a quick example:

sort(arr, arr+5);
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}

Output:

1 2 4 6 9

reverse()

The reverse() function reverses the order of elements in the specified data structure. It accepts two parameters: the starting iterator and the ending iterator.

Syntax:

reverse(start_iterator, end_iterator);

Here's a short example for the above method:

reverse(arr, arr+5);
for(int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}

Output:

4 1 9 2 6

*min_element() and *max_element()

The functions *max_element() and *min_element() return the maximum and minimum value inside the specified data structure, respectively. Both these functions accept two arguments: the start iterator and the end iterator.

Syntax:

*max_element(start_iterator, end_iterator);
*min_element(start_iterator, end_iterator);

Let’s find out what values these functions return upon calling them on the example array:

cout << *max_element(arr, arr+5) << endl;
cout << *min_element(arr, arr+5) << endl;

Output:

9
1

The binary_search() method is used to find whether the specified value is present inside the data structure or not. It accepts three arguments: the starting iterator, the ending iterator, and the value that you want to find.

Binary search only works on sorted data structures. Therefore, you'll need to call the sort() method first before the binary_search() method.

Syntax:

binary_search(start_iterator, end_iterator, value_to_find)

Here's a demonstration of this method:

sort(arr, arr+5);
binary_search(arr, arr+5, 2) ? cout << "Element found" : cout << "Element not found";
binary_search(arr, arr+5, 7) ? cout << "Element found" : cout << "Element not found";

Output:

Element found
Element not found

count()

The count() method returns the count of occurrence of the specified value inside the data structure. It takes three arguments: the start iterator, the end iterator, and the value to count.

Syntax:

count(start_iterator, end_iterator, value_to_count);

Here's an example of this method:

cout << count(arr, arr+5, 2) << endl;

Output:

1

Containers in STL

Containers are the data structures that store objects and data. Vectors, lists, stacks, queues, sets, and maps are some of the examples that store data in them according to the specified primitive datatype. You can use these containers by importing their respective headers in the C++ file.

While initializing the container variable, you need to mention the primitive data such as intcharstring inside the <> brackets.

Let's explore some of these containers in greater detail:

Vector

Vectors are dynamic arrays that are resizable and flexible to work with. When you insert or delete an element from the vector, it automatically adjusts the vector's size. This is similar to the ArrayList data structure in Java.

Syntax:

#include <vector>
vector<data_type> variable_name;

Here are some important vector methods:

  1. push_back(value): This method appends the data to the vector.
  2. pop_back(): This method removes the last element from the vector.
  3. insert(index, value): This method inserts new elements before the element at the specified position.
  4. size(): This method returns the size of the vector.
  5. empty(): This method checks whether the vector is empty or not.
  6. front(): This method returns the first value of the vector.
  7. back(): The back method returns the last value of the vector.
  8. at(index): This method returns the value at the specified position.
  9. erase(index): The erase method removes elements from the given index.
  10. clear(): This method clears all the items in the vector.
vector < int > v = { 23, 12, 56, 10 };
v.push_back(5);
v.push_back(25);
v.pop_back();
auto i = v.insert(v.begin() + 1, 7);
cout << "The size of the given vector " << v.size() << endl;
if (v.empty()) {
cout << "Vector is empty" << endl;
} else {
cout << "Vector is not empty" << endl;
}
cout << "Element at the first position is " << v.front() << endl;
cout << "Element at the last position is " << v.back() << endl;
cout << "Element at the given position is " << v.at(4) << endl;
v.erase(v.begin() + 1);
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}

Output:

The size of the given vector 6
Vector is not empty
Element at the first position is 23
Element at the last position is 5
Element at the given position is 10
23 12 56 10 5

Queue

In the queue data structure, elements are inserted from the back and deleted from the front. Hence, it follows the FIFO ("first in, first out") approach.

Syntax:

#include <queue>
queue<data_type> variable_name;

Here are some important queue methods:

  1. push(value): This method adds elements to the queue.
  2. pop(): This method deletes the first element of the queue.
  3. size(): This method returns the size of the queue.
  4. front(): This method returns the first element of the queue.
  5. back(): This method returns the last element of the queue.
queue < int > q;
q.push(30);
q.push(40);
q.push(50);
q.push(60);
q.push(70);
cout << "The first element is " << q.front() << endl;
cout << "The last element is " << q.back() << endl;
cout << "The size of queue is " << q.size() << endl;
q.pop();
cout << "Printing all the elements of the Queue" << endl;
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}

Output:

The first element is 30
The last element is 70
The size of the queue is 5
Printing all the elements of the Queue
40 50 60 70

Stack

Stack containers operate on the LIFO method. LIFO stands for "last in, first out". Data is pushed and popped from the same end.

Syntax:

#include <stack>
stack<data_type> variable_name;

Here are some important stack methods:

  1. push(value): This method pushes the element in the stack.
  2. pop(): This method deletes the top element of the stack.
  3. top(): This method returns the value of the last element entered in the stack.
  4. size(): This method returns the size of the stack.
  5. empty(): This method checks whether the stack is empty or not.
stack < int > s;
s.push(30);
s.push(40);
s.push(50);
s.push(60);
cout << "The top of the stack contains " << s.top() << endl;
s.pop();
cout << "The top of the stack after performing pop operation: " << s.top() << endl;
cout << "Printing all elements of the stack" << endl;
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}

Output:

The top of the stack contains 60
The top of the stack after performing pop operation: 50
Printing all elements of the stack
50 40 30

Set

Set containers are used to hold unique values, and the value of the element can't be changed once it's inserted into the set. All the elements in the set are stored in a sorted manner. The set container is similar to the set data structure in Python.

Syntax:

#include <set>
set<data_type> variable_name;

Here are some important set methods:

  1. insert(value): This method inserts elements in the set.
  2. begin(): This method returns the iterator to the first element of the set.
  3. end(): This method returns the iterator to the last element of the set.
  4. size(): This method returns the size of the set.
  5. empty(): This method checks whether the set is empty or not.
  6. find(value): This method returns the iterator to the element passed in the parameter. If the element is not found then this function returns the iterator to the end of the set.
  7. erase(value): This method deleted the specified element from the set.
set < int > s;
s.insert(20);
s.insert(30);
s.insert(40);
s.insert(50);
s.insert(60);
s.insert(60);
s.insert(60);
auto i = s.begin();
cout << "Element at the first position " << * i << endl;
cout << "The size of the set " << s.size() << endl;
s.find(20) != s.end() ? cout << "Element found" << endl : cout << "Element not found" << endl;
s.erase(30);
cout << "Printing all the elements" << endl;
for (auto i = s.begin(); i != s.end(); i++) {
cout << * i << " ";
}

Output:

Element at the first position 20
The size of the set 5
Element found
Printing all the elements
20 40 50 60

C++ Doesn't Have to Be Hard

Just like every other skill, practice is essential to make the most out of the STL. These containers and algorithms can help you save a lot of time and are easy to use. Start by practicing the examples shown above and you'll eventually start to use it in your own projects as well.

However, if this your first time learning C++, start by learning the basics before you proceed to understand the STL.


Post a Comment

0 Comments