×

C++ STL (Standard Template Library)

Introduction

C++ is a flexible type and general proposed programming language. So we need a standard library that supports C++. C++ STL (Standard Template Library) is a collection of templates that contains iterators, algorithms, and function objects.

In this article, we are going to learn about C++ STL (Standard Template Library).

Generic Programming

Generic programming is an approach that looks into designing and implementing data structure and algorithms in such a way that there is no loss of efficiency. It is also defined in another way that generic programming is a way of writing software that allows us to reuse the code without losing efficiency. For example: STL (Standard Template Library).

What is C++ STL (Standard Template Library)?

STL is abbreviated as Standard Template Library. It was invented by Alexander Stepanov in the year of 1994. The standard library contains an algorithm and data structure. With the help of STL (Standard Template Library), we can store and manipulate the object. By using STL (Standard Template Library), we can make a program robust and reusable.

Components of STL (Standard Template Library)

STL (Standard Template Library) has four components. These are as follows.

  1. Containers.
  2. Iterators.
  3. Algorithms.
  4. Function objects.

Let's discuss each component one by one.

1. Containers

If we have many elements then we need a container to sort those elements. With the help of a container, we can store the collection of data. It also helps us to implement and recreate complex data smoothly.

C++ STL (Standard Template Library)

The container is classified into three categories. These are as follows.

  • Sequence containers
  • Associative containers
  • Containers adapters

Sequence containers

  • It is used to store the sequential data structure like an array and linked list etc.
  • Vectors: It can be defined as a dynamic array with some extra features.

Syntax:  

vector<int> v;
  • Deque: it is also known as a double-ended queue. It allows us to insert and delete from both ends. It is more efficient than the vector.

Syntax:

deque<int> d;
  • List: it is also called the sequential container. It also allows non-contiguous allocation. With the help of a list, we can perform deletion and insertion anywhere in the sequence.

Syntax:

list<int> l;

Associative containers

  • It is used to store the element in which each element is related to a particular key. It is also used to store the sorted data structure like maps, sets and multi-sets etc.
  • Set: It is used to store the unique element.

Syntax:

set<int> s;
  • Multiset: It is similar to a set container. But it only stores non-unique elements.

Syntax:

multiset<int> m;
  • Map: It is used to store the set of key-value pairs in which each key is associated with one value.

Syntax:

map<int,int> mm;

Where int is key type and value type.

  • Multimap: It is used to store the set of key-value pairs in which each key is associated with a duplicate value.

Syntax:

multimap<int,int> mm1;

Containers adapters

  • It is used to define the container as an interface where it provides functionality to pre-existing containers.
  • Stack: It follows the last-in, first-out (LIFO) approach. It means new elements are added at the last and removed from that end.
  • Queue: It follows the first-in, first-out (FIFO) approach. It means new elements are added from the end and removed from the front.

Example of container

#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v;
for(int i=1; i<=21; i++)
{
v.push_back(i);
}
cout <<"Size : "<< v.size();
v.resize(12);
cout <<"\nAfter resizing it becomes : "<< v.size();
if (v.empty() == false)
{
cout <<"\nNot empty";
}
else{
cout <<"\nVector is empty";
}
cout <<"\n Elements of vector: ";
for (auto it = v.begin(); it != v.end(); it++)
{
cout << *it <<"";
}
return 0;
}

Output:

Size: 21
After resizing, it becomes: 12
Not empty
Elements of vector: 1 2 3 4 5 6 7 8 9 10 11 12

In the above example, the vector function and some other functions combinedly perform the operation. When the vector v is declared, we add the push_back() function to help the loop. After that, with the help of the size() function, we display the length of the vector. Now with the help of resize() function, we set the vector size to 12. Then we check if the vector is empty or not with the help of the empty() function. Now we display all the vector elements with the help of a loop and functions like begin() and end().

2. Iterators

With the help of iterators, we can access the element that is present inside the container. It helps us to traverse the element in the container. Iterators can be incremented and decremented. There are two types of iterator functions. These are as follows.

  • Begin(): With the help of these, we can iterate the first element of the container.
  • End(): With the use of these, we can repeat the last element of the container.

Iterators have been categorised into five types. These are as follows.

(a) Input iterator

  • It is a type of iterator by which we can read the value from the container.
  • It is a one-way iterator.
  • It can be incremented, but it cannot be decremented.

(b) Output iterator

  • With the help of the output iterator, we can modify the data inside the container, but we cannot read it.
  • It is also a one-way iterator.
  • Writing of data is only possible with the help of the Output iterator.

(c) Forward iterator

  • In Forward iterator, we can navigate through the container with the help of the ++ operator.
  • It can pass through each element in the container one element at a time.

(d) Bidirectional iterator

  • It is similar to the forward iterator. It also moves in a backward direction.
  • So it is a two-way iterator.
  • It can be both incremented and decremented.

(e) Random Access Iterator

  • It is used to access the random element in the container.
  • It supports all the features of the bidirectional iterator. 
  • It also supports pointer addition.
  • With the help of pointer addition, we can access the random element in the container.

Example of iterators

#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
int main()
{
 vector<int> ar = { 7, 8 , 9, 10 , 11};
 vector<int>::iterator ptr;
 cout <<"The vector elements are : ";
 for (ptr = ar.begin(); ptr < ar.end(); ptr++)
 {
 cout << *ptr <<"";
 }
 return 0;
}

Output:

The vector elements are: 7 8 9 10 11 

3. Algorithm

There are different types of algorithms that can be implemented with the help of an iterator. It is defined as a function that can be applied to the container and provide the operations to the container. For example: sort(), swap(), min(), max() etc.

The algorithm has been categorised into five types. These are as follows.

  • Nonmutating algorithms.
  • Mutating algorithms.
  • Sorting algorithms.
  • Set algorithms.
  • Relational algorithms.

(a) Nonmutating algorithms

  • It is a type of algorithm in which we cannot alter the value of the container.
  • It also cannot change the order of the element.
  • This algorithm utilised the use of forwarding iterators.

(b) Mutating algorithms

  • It is a type of algorithm in which we can alter the value of the container.
  • It also can change the order of the element.

(c) Sorting algorithms

  • With the help of a sorting algorithm, we can modify the element inside the container.

(d) Set algorithms

  • It is also known as a sorted range algorithm.
  • With the help of this algorithm, we can perform some functions on the element inside the container.

(e) Relational algorithms

  • With the help of this algorithm, we can work on numerical data. 
  • It is mainly designed for mathematical calculation.

4. Function object

It is also known as a functor. It is a function that defines the object. It is used to extend the characteristics of regular function. It has both member function and member attributes. It can also be initialised before usage.

Example of function object

#include <iostream>
using namespace std;


class Add {


public:
int operator() (int p, int q) {
return p + q;
}
};


int main() {
Add add
int sum = add(555, 666);


cout <<"The sum of 555+666 is "<< sum;


return 0;
}

Output:

The sum of 555+666 is 1221

Related Topics

How the value is passed in C++

Introduction: The call-by-value method of giving arguments to a function duplicates the real value of an argument into the formal parameter of the function. In this instance, modifications to the parameter...

5 minutes read.

Functions in C++ with Types and Examples

A function is a collection of statements that work together to complete a certain goal. It could consist of statements that execute repetitive operations or statements that conduct specialized jobs...

10 minutes read.

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.

Loops in C++

A loop statement in most programming languages allows us to execute a statement or a collection of statements numerous times. Control structures of programming languages vary, allowing for more complex...

6 minutes read.

C++ Try-Catch

Every useful program will eventually encounter unexpected outcomes. By entering data that are incorrect, users might create mistakes. Sometimes the program's creator didn't consider all of the options or was...

7 minutes read.

C++ First Program

Let's write a simple basic program structure of C++, its compilation and its execution (how it runs). This program is compiled using GCC compiler. Open any editor to write C++ program. #include<iostream>   using namespace std;   int main(){       cout<<"Welcome to C++ program"<<endl;   } Output...

2 minutes read.

C++ If-else-if

Introduction: If-else-if control statement is an if statement used with an optional else if control statement to check multiple conditions. In this control statement, when any one of the condition returns...

4 minutes read.

Check for Balanced Brackets in an Expression (well-formedness) using Stack

Write a program that check the correctness of the pairs and ordering of the characters “{“, “}”, “(“, “)”, “[“, “]” in the expression string exp. Example: Checking for balanced parenthesis is one of...

2 minutes read.

Returning a Function Pointer from a Function in C/C++

Pointers to functions can be used in the C programming language just like standard data pointers such as "int *," "char *," etc. The following is a basic example of a...

3 minutes read.

Hello World Program in C++

The steps for “Hello World” C++ program are as follows: Write a C++ code given below in an editor. Save the file with .cpp Compile the code using C++ compiler or using online...

3 minutes read.

C++ if-else

C++ if else Control Statement if else control statement in C++ is used to control the program flow in a two-way direction. When condition returns a true value, then the program executes if condition block otherwise...

1 minute read.

Structure Vs Class in C++

The structure in C++ is similar to that of a class, with a few exceptions. Both the structure and the stage, the most important thing is safety. The property is...

4 minutes read.

Top 14 Best Free C++ IDE (Editor & Compiler) for Windows in 2024

Bjarne Stroustrup created the all-purpose object-oriented programming language C++. To develop C++ programs, there are various Integrated Development Environments (IDE) that offer prewritten code templates. These programs automatically modify the...

6 minutes read.

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the...

3 minutes read.

LCM Program in C++

What is LCM? LCM is an acronym for "least common multiple". It is used to discover the lowest positive integer divisible by all integers (whose LCM is calculated). For instance, the...

4 minutes read.

Octal to Decimal in C++

We need to write a system that converts octal number into equal decimal number when octal number is given as input. Let us look at an example of a program in...

2 minutes read.

How to create a library in C++

Before going on to the creation of a library, let’s understand its meaning. What is a library? In simple words, a library is a collection of numerous functions, methods, classes, header files...

7 minutes read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

C++ Queue

C++ queue: Queue in C++ is also a container adapter with the functionality of a queue. Queue is just the opposite of the stack in C++ because stack works on...

4 minutes read.

External merge sort in C++

External merge sort in C++ External sorting is a concept for a group of sorting algorithms capable of handling large data volumes. External sorting is needed if the information getting sorted...

9 minutes read.