May 11, 2021 C++
In the previous sections, we've already learned the concept of a C++ template. The C++ STL (Standard Template Library) is a powerful set of C++ template classes that provide common template classes and functions that enable a variety of popular and commonly used algorithms and data structures, such as vectors, lists, queues, and stacks.
The core of the C++ standard template library consists of three components:
Assembly | describe |
---|---|
Containers | The container is used to manage a collection of some types of objects.C ++ provides a variety of different types of containers, such as Deque, List, Vector, Map, etc. |
Algorithms | The algorithm acts on the container.They provide a way to perform a variety of operations, including initialization, sort, search, and conversion of the container content. |
Iterators | The iterator is used to traverse the object set.These collections may be containers, or the subset of containers. |
All three components come with rich predefined functions that help us handle complex tasks in a simple way.
The following program demonstrates a vector container (a template for the C++ standard), which is very similar to an array, but the only difference is that the vector automatically handles its own storage needs when it needs to scale up:
#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 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
There are a few things to note about the various functions used in the example above: