WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

C++ STL tutorial


In the previous chapter, we have learned the concept of C++ templates. C++ STL (Standard Template Library) is a powerful set of C++ template classes that provides generic template classes and functions that implement a variety of popular and commonly used algorithms and data structures such as vectors, linked lists, and queues. , stack.

The core of the C++ standard template library consists of the following three components:

The The The
Components Description
Containers container is a collection used to manage a certain type of object. C++ provides a variety of different types of containers, such as deque, list, vector, map, and more.
Algorithms algorithm acts on the container. They provide a way to perform various operations, including performing initialization, sorting, searching, and converting on container content.
itererators iterator is used to traverse the elements of the object collection. These collections may be containers or a subset of them.

These three components come with a wealth of predefined functions that help us handle complex tasks in a simple way.

The following program demonstrates a vector container (a C++ standard template) that is very similar to an array, except that the vector automatically handles its own storage needs when it needs to be expanded:

Instance

#include <iostream> #include <vector> using namespace std; int main() { // Create a vector store int vector<int> vec; int i; // Display the original size of vec cout << "vector size = " << vec.size() << endl; // Push 5 values into the vector for(i = 0; i < 5; i++){ vec.push_back(i); } // Display the size of the vec extension cout << "extended vector size = " << vec.size() << endl; // 5 values in the access vector for(i = 0; i < 5; i++){ cout << "value of vec [" << i << "] = " << vec[i] << endl; } // Use the iterator iterator to access the value vector<int>::iterator v = vec.begin(); while( v != vec.end()) { cout << "value of v = " << *v << endl; v++; } return 0; }

When the above code is compiled and executed, it produces the following results:

Vector size = 0
Extended vector size = 5
Value of vec [0] = 0
Value of vec [1] = 1
Value of vec [2] = 2
Value of vec [3] = 3
Value of vec [4] = 4
Value of v = 0
Value of v = 1
Value of v = 2
Value of v = 3
Value of v = 4

A few points to note about the various functions used in the above examples:

  • Push_back( ) The member function inserts a value at the end of the vector and expands the size of the vector if necessary.
  • The
  • size( ) function displays the size of the vector.
  • The
  • begin( ) function returns an iterator pointing to the beginning of the vector.
  • The
  • end( ) function returns an iterator pointing to the end of the vector.