STL Classes in C++

STL Classes in C++ with Examples:

In this article, I am going to discuss STL Classes in C++ with Examples. Please read our previous article where we discussed what are STL and why we need STL in C++ Language.

STL Classes in C++

Standard Template Library i.e. STL contains Algorithms, Containers, and Iterators. Let us understand these terms first.

What are Algorithms?

These are built-in algorithms or functions that are meant for managing containers i.e. performing operations on the containers.

What are containers?

Array, Linked List, Stack, Queue, etc. all are containers. For these containers, there are built-in classes available in C++. Those built-in classes are known as containers. A container contains a collection of data or a list of data.

What are iterators?

There are iterators for iterating through the collection of values. So, for accessing the containers, iterators are available. If this is not clear at the moment, then don’t worry, we will discuss these things in detail with examples.

So let us proceed further and briefly discuss these three things.

Algorithms:

We have algorithms for searching in a collection. It means we can search for a particular element in arrays, linked lists, queues, stacks, etc. And we can also sort the data structure. We can perform a binary search; we can reverse a data structure means a collection of elements. The functions are available for performing these operations. So, you can explore these functions and use them.

Some of functions are- search(), sort(), binary-search(), reverse(), Concat() (it concatenate two collections), copy() (it will copy one collection into another collection), union(), intersection(), merge() (it will perform merge sort), Heap() and many more functions are available in C++. The exact function names may differ but the purpose of the functions will be the same.

Containers:

Following is the list of the containers that are available in C++,

  1. Vector
  2. List
  3. Forward_List
  4. Deque
  5. Priority_Queue
  6. Stack
  7. Set
  8. Multiset
  9. Map
  10. MultiMap

These are all container classes. And all these classes are template classes. This means these are generic, and they can work with any type of data. Now let us see how these are implemented.

Vector Container Class in C++:

It is nothing but the array only. But this is not fixed sized array. This can grow and reduce by itself. How an array can reduce by itself? We have shown this in our previous articles that we have to create a bigger or small size array and transfer the elements into the new array. So, the vector automatically manages that part. This will dynamically manage the size of the array. So, this is a self-managed array. Functions available in Vector are as follows:

  1. push_back(): It will insert the element at the back in an array.
  2. pop_back(): It will delete the last element in the array.
  3. insert(): It will insert the given value at the given index.
  4. remove(): It will remove the element by the given index.
  5. size(): It will return the size of the array.
  6. empty(): It will check whether the array is empty or not.
List Container Class in C++:

This class is for a doubly linked list. Already we have shown you that the doubly linked list has two pointers, one is in the forwarding direction and one is in the backward direction as shown in the below image.

List Container Class in C++

We don’t have to write down the code for creating a linked list in C++. We can directly use the list class as a template class. We can have a linked list of float, int, double, or our object. That means we can create a linked list of any type. Then what are the functions it is having? It is having the same function that a vector has. But some different functions are as follows:

  1. push_front(), pop_front(): With these functions, we can insert or delete from starting of the liked list
  2. front() and back(): These functions will return the first and the last element.

So, insertion and deletion in the linked list are possible from both ends.

Forward_List Container Class in C++:

This is a singly linked list so that’s why the name is forward_list. You can access elements in the only forward direction. It points to the next node. You can use this list if you want to access elements in the only forward direction. Function in forward_list: push_front(), pop_front(), push_back(), pop_back(), insert(), remove(), size(), empty(), front(), back() etc.

Deque:

Deque is the same as a vector. It means a double-ended queue means you can insert or delete from both ends in an array. It is also having the same set of functions as of list class. List, forward_list, and deque have the same set of functions. Only in vector, we cannot delete or insert from the front. But in deque, we can insert or delete from any end. But insertion and deletion are easy in singly and doubly linked lists.

Priority_Queue:

It is for the heap data structure. It is having the functions: push () and pop () for inserting and deleting. These operations are for the stack as well as for priority_queue also. It is having empty () and size () functions.

Priority queue means always the largest element from the queue will be deleted. It is not in the ordered form. It will always delete the max element from the queue.

Stack:

This works on the discipline LIFO which is last in first out. It is having the same set of operation that a priority_queue have.

Set:

This is a collection of elements that will contain unique elements. Duplicate elements are not allowed in the set. It will not maintain order.

Multiset:

This is the same as the set but it allows duplicating.

Map:

This data structure is useful for storing key and value pair: <key: value>. For example,

Whenever you want to find any value then we will give the key then we will get the value. The map data structure uses a hash table. And it will contain unique keys.

Multi Map:

This is the same as the map but keys can be duplicated the same key-value pair should not be duplicated in Multi map.

How to use STL Container Classes in C++?

Let us look at the example of how we use these STL Classes in C++. So first we are taking an example of the vector. Let us create an object of vector and insert some elements in this one. For using a vector, we must include <vector> which is the vector header file.

#include <vector>
int main()
{
       vector < int >v = { 20, 30, 50, 70 };
}

As you can see in the above code, inside the main function, we have created an object v of type vector STL Class. As vector is a type of template, so we should mention the type of data we want to store in this object. Here, we have given the type as int. So instead of int, you can give any primitive data type like float, char, etc. Apart from the built-in primitive data type, we can write our own user-defined classes like Employee, Student, etc., and store the objects in the vector.

If you want then you can give the size to the vector, like v(10). If you want some initial values in this vector object then you can mention them inside the bracket like {20, 30, 50, 70}. We have given some values inside the curly brackets. We know already that vectors use an array. Then after this if you want to insert more values, you can insert them as follows:

v.push_back(43);
v.push_back(52);

So, 43 and 52 will be inserted at the end of vector v. And if we want to delete the values then you can delete them as follows:

v.pop_back(); This will delete the last value from the vector v. So, 52 will be deleted. We can also use other functions such as insert, remove, etc.

Now let us see how to iterate through this list of elements. We want to access all the elements of the vector object either for printing the elements or to perform some other operation. So let us see how to use an iterator to access all the vector collection elements.

There is a for each loop that was introduced in C++ 11. We can use that for each loop to iterate over all the elements of a collection like a vector in C++ as follows:

for(int x: v)
{
      cout << x << endl;
}

In this loop, all the elements from the vector will come one by one and will store in the x variable. Here, the important point that you need to remember is the x variable data type and the vector data type should be the same. This is the simplest iterator that is provided by C++ 11. So, foreach loop can be used for iterating through all these elements.

In the second method, there are some iterator classes available in C++. We can use the iterator classes to iterate over all the collection elements as follows:

Vector<int>::iterator itr = v.begin();

This iterator class belongs to the vector class. We have created an object itr of type iterator. We must assign this iterator object. So we assigned it to v.begin(). This is an important function. Begin function will start the iterator. This begin function is available in all the containers. Begin is the start of the collection and the end function gives the end of the collection. There are similar functions also that are rbegin() and rend() that give the end of the collection.

There are other functions also like rbegin and rend which help in traversing a collection from the rare end. So reverse traversing is possible. So let us use this iterator and access all the elements.

vector <int>::iterator itr;
for (itr = v.begin(); itr != v.end(); itr++)
{
      cout << *itr << endl;
}

We have used *(asterisk) because the iterator is like a pointer to the elements inside the collection. So, we can dereference itr object and print those elements. From beginning to end, we have iterated through the vector v with the help of for loop and iterator class. So, iterators are available in every collection. That’s it. It is so easy to use an array and also iterate through all the elements. Now we don’t have to worry about the array whether it is full or not. For insertion also, we can simply insert with the insert function.

Next, the very important thing is, instead of a vector in the above code, can we write the same for the list? Yes, look at the following code.

#include <iostream>
using namespace std;
#include <list>
int main()
{
    list <int> l = {20, 30, 50, 70};
    l.push_back(23);
    l.pop_back ();

    list <int>::iterator itr;
    for (itr = l.begin(); itr != l.end(); itr++)
    {
        cout << *itr <<endl;
    }
}

This is a program using the list. So, everything remains the same as in the vector. Now, instead of a vector, we have used a list. It is so easy to change the data structure. Now, instead of a list, we can use this program for forward_list also. We can also make this a set also. But in set and forward_list, there are no push_back and pop_back functions. So, we have to use different functions for the set. Like, as insert and remove functions.

But for vector, list, forward_list, or deque, operations remain the same. So, we don’t have to worry about how the data is stored. You should focus on what data you want to store and how you want to access that.

So, C++ STL classes give peace of mind for programmers to manage their data easily. Now let us look at the complete program for different data structures.

Example to understand vector STL Container Class in C++:
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> v = { 20, 30, 50, 70 };
    v.push_back(23);
    v.pop_back();

    cout << "Using Iterator:" << endl;
    vector < int >::iterator itr;
    for (itr = v.begin(); itr != v.end(); itr++)
    {
        cout << *itr << endl;
    }

    cout << "Using Foreach Loop:" << endl;
    for (int x:v)
    {
        cout << x << endl;
    }
}
Output:

Example to understand vector STL Container Class in C++

Example to understand List STL Container Class in C++:
#include <iostream>
#include <list>
using namespace std;
int main()
{
    list <int> l = { 20, 30, 50, 70 };
    l.push_back(23);
    l.pop_back();

    cout << "Using Iterator:" << endl;
    list < int >::iterator itr;
    for (itr = l.begin(); itr != l.end(); itr++)
    {
        cout << *itr << endl;
    }

    cout << "Using Foreach Loop:" << endl;
    for (int x:l)
    {
        cout << x << endl;
    }
}
Output:

Example to understand List STL Container Class in C++

Example to understand Forward List STL Container Class in C++:
#include <iostream>
#include <forward_list>
using namespace std;

int main()
{
    forward_list<int> fl = { 20, 30, 50, 70 };
    fl.push_front (23);
    fl.pop_front ();

    cout << "Using Iterator:" << endl;
    forward_list < int >::iterator itr;
    for (itr = fl.begin (); itr != fl.end (); itr++)
    {
        cout << *itr << endl;
    }

    cout << "Using Foreach Loop:" << endl;
    for (int x:fl)
    {
        cout << x << endl;
    }
}
Output:

Example to understand Forward List STL Container Class in C++

Example to understand Set STL Container Class in C++:
#include <iostream>
#include <set>
using namespace std;
int main()
{
    set <int> s = { 20, 30, 50, 70 };
    s.insert (23);
    s.erase (23);

    cout << "Using Iterator:" << endl;
    set <int>::iterator itr;
    for (itr = s.begin(); itr != s.end(); itr++)
    {
      cout << *itr << endl;
    }

    cout << "Using Foreach Loop:" << endl;
    for (int x:s)
    {
      cout << x << endl;
    }
}
Output:

Example to understand Set STL Container Class in C++

Map STL Container Class in C++:

Now, we will see how to use map data structure in C++. Map stores the elements in the form of key-value pair. Let us create an object of map STL Container class as follows.

#include <iostream>
using namespace std;
#include <map>
int main()
{
    map <int, string> m;
    m.insert(pair <int, string> (1, "Vishal"));
    m.insert(pair <int, string> (2, "Shivam"));
    m.insert(pair <int, string> (3, "Ishika"));
}

For using the map STL Class in C++, we have included the map header file. Inside the main function, we have created an object m of type map<int, string>. This object will hold the list of the pairs of type <int, string>. Then we used the insert() function to insert some values in the m object. Can we iterate through the map? Yes, there is an iterator available for the map as follows.

map<int, string>::iterator itr;
for(itr = m.begin(); itr!= m.end(); itr++)
{
      cout << itr->first << ” ” << itr->second << endl;
}

We created an object itr of type iterator of the map. As we discussed that every container has an iterator class so the map also contains an iterator class. When you run the above code of lines the output will be,

1 Vishal
2 Shivam
3 Ishika

Let us see the complete program.

Example to understand Map STL Container Class in C++:
#include <iostream>
using namespace std;
#include <map>
int main()
{
    map <int, string> m;
    m.insert(pair <int, string> (1, "Vishal"));
    m.insert(pair <int, string> (2, "Shivam"));
    m.insert(pair <int, string> (3, "Ishika"));
    map <int, string>::iterator itr;
    for (itr = m.begin(); itr != m.end(); itr++)
    {
        cout << itr->first << " " << itr->second << endl;
    }
}
Output:

Example to understand Map STL Container Class in C++

In the next article, I am going to discuss Containers in C++ with Examples. Here, in this article, I try to explain STL Classes in C++ with Examples and I hope you enjoy this article. I would like to have your feedback. Please post your feedback, question, or comments about this STL Classes in C++ with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *