C++ STL Tutorial


In the previous chapters, we have learned the concept of C++ templates. C++ STL (Standard Template Library) is a set of powerful C++ template classes that provides common template classes and functions. These template classes and functions can 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 includes the following three components:

ComponentDescription
ContainersContainers are used to manage a collection of objects of a certain type. C++ provides various types of containers, such as deque, list, vector, map, etc.
AlgorithmsAlgorithms act on containers. They provide ways to perform a variety of operations, including initializing, sorting, searching, and transforming the contents of the container.
Iterators (iterators) Iterators are used to traverse the elements of an object collection. These collections may be containers or subsets of containers.

These three components all come with rich predefined functions to help us handle complex tasks in a simple way.

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

#include <iostream>
#include <vector>
using namespace std;
 
int main()
{
   // 创建一个向量存储 int
   vector<int> vec; 
   int i;

   // 显示 vec 的原始大小
   cout << "vector size = " << vec.size() << endl;

   // 推入 5 个值到向量中
   for(i = 0; i < 5; i++){
      vec.push_back(i);
   }

   // 显示 vec 扩展后的大小
   cout << "extended vector size = " << vec.size() << endl;

   // 访问向量中的 5 个值
   for(i = 0; i < 5; i++){
      cout << "value of vec [" << i << "] = " << vec[i] << endl;
   }

   // 使用迭代器 iterator 访问值
   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 will produce 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

There are a few things to note about the various functions used in the above example:

  • push_back( ) member function inserts a value at the end of the vector, extending the vector's size if necessary.

  • size( ) function displays the size of a vector.

  • begin( ) function returns an iterator pointing to the beginning of the vector.

  • end( ) function returns an iterator pointing to the end of the vector.