×

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

Initialize Array of objects with parameterized constructors in C++

Initialize Array of objects with parameterized constructors in C++ When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to...

3 minutes read.

Dynamic Memory Allocation in C++

In some programming situations, the number of data items changes as the program is running, which is known as dynamic data or input. Consider a real-world situation where a program...

3 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

5 minutes read.

Dynamic _Cast in C++

C++ is one of the most powerful programming languages. We can write object-oriented and structured programming with the help of C++. In this article, we will learn about the dynamic...

3 minutes read.

Factorial of a Number in C++ using while Loop

What is a factorial? The factorial of a number is the product of all the positive numbers less than or equal to n, indicated by n! According to the standard for an...

6 minutes read.

Armstrong Number using While Loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

4 minutes read.

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

Vector Size in C++

What are Vectors?  In the C++ programming language, vectors are run-time sequence containers representing arrays with variable sizes, which are contained within STL (Standard Template Library). They utilize contiguous storage spaces...

6 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 minutes read.

Template Specialization in C++

Template is a feature of C++. With the help of a template, we can write the code only once and use that code multiple times. For example, there is a...

4 minutes read.

C++ Program to Print Fibonacci Triangle

Fibonacci Triangle Program in CPP Definition: Fibonacci Triangle as the name suggests is the same as the Fibonacci number series where the next element is the sum of the previous two elements....

3 minutes read.

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

4 minutes read.

C++ Overloading

C++ Overloading is a condition when two or more members have the same name with different parameter type or a different number of parameter. C++ overloading is two types: Function...

1 minute read.

This keyword in C++

This keyword in C++ is a pointer which points to the object. It is passed as an argument to functions which helps in accessing the object. It is used for a...

3 minutes read.

Iostream in C++

Using Iostream in C++, we can perform input and output operation capabilities. This represents input and output, and the stream is used to carry out this capability. A stream is...

4 minutes read.

Memset in C++

Memset () is a function in the C++ programming language that fills memory blocks. The value of "ch" is first converted to an unsigned character. In this case, "ch" denotes the...

3 minutes read.

fread() Function in C++ Programming

C++ language is used to make high-performance applications that can work efficiently, and it is one of the world's most popular languages. It is an object-oriented and high-level programming language;...

3 minutes read.

Scope Resolution Operator in C++

The scope resolution operator and its different usage in the C++ programming language will be discussed in this section. The scope resolution operator is used to refer to an out-of-scope...

6 minutes read.

Features of OOPS in C++

What is OOPs? The main reason programmers prefer C ++ language over C is because of the support of object-oriented programing in C++. As the name suggests, object-oriented programming or OOPs...

3 minutes read.

Decimal to Octal in C++

We must create a software that converts a decimal number into an equal octal number given a decimal number as input i.e. convert a number having a base value of...

3 minutes read.