STL是C++的一个重要组成部分。
我们使用C++的理由,无非3种:
- C++对C的兼容与扩展
- C++面向对象
C++ STL
在本系列blog中,我们就简单的介绍一下STL的用法。
什么是STL?
STL的全称为standard template library,标准模板库。这个库里面有c++大牛封装的一系列代码。我们学习STL的目的不是分析STL源码然后写出跟STL中一样性能强悍的代码,而是学会使用STL已经集成好了的工具,去解决我们现实中所遇到的问题。研究STL源码是专注于高性能C++代码的工程师的工作,作为初学者,熟练使用各种API,能够解决LeetCode上的算法题,这就够了。需要提一句,stl中所用容器算法都在命名空间std中。STL中有什么?
STL可以分为:容器(container),算法(algorithm)和迭代器(iterator)。当然STL中还有allocator,adapters和functors,我们遇到他们的时候再谈论他们,我们先关注容器算法和迭代器。- 容器
我们可以把容器理解为数据结构。容器的最主要的功能就是存储数据。
容器分为顺序容器(序列式容器)和关联式容器。
- 序列式容器:容器中元素的在容器中的存储位置随着元素进入容器的时间和地点而改变。
- vector
- deque
- stack
- queue
- list
- 关联式容器:容器中元素在容器中的存储位置跟元素进入容器的时间和地点无关。(基于二叉树实现的)
- set
- multiset
- map
- multimap
- 序列式容器:容器中元素的在容器中的存储位置随着元素进入容器的时间和地点而改变。
迭代器
迭代器的功能和指针很像。迭代器是对指针的封装。
迭代器最主要的功能是对容器中的数据进行遍历。同时建立容器与算法之间的关系。
迭代器分为:- 前向迭代器
- 双向迭代器
- 随机访问迭代器
算法
算法是解决问题的方法。
这个之前说过很多次了,在这里不重复了。
- 容器
在STL中容器和算法分离,那容器迭代器和算法是如何工作的呢?
容器中可以存放标准数据类型,对象和指针。以及容器(容器嵌套容器)。
写个例子来说明容器可以存放标准数据类型,对象和指针:#include <iostream> #include <vector> #include <algorithm> using namespace std; void test_1(){ vector<int> v; v.push_back(10); v.push_back(20); v.push_back(30); vector<int>::iterator pStart = v.begin(); vector<int>::iterator pEnd = v.end(); while (pStart != pEnd){ cout << *pStart << endl; pStart++; } } class Teacher{ public: int id; int age; Teacher(int id, int age) :id(id), age(age){} }; void test_2(){ vector<Teacher> v; Teacher t1(1, 2), t2(3, 4), t3(5, 6); v.push_back(t1); v.push_back(t2); v.push_back(t3); vector<Teacher>::iterator pStart = v.begin(); while (pStart != v.end()){ cout << "ID:" << (*pStart).id << " Age:" << pStart->age << endl; pStart++; } } void test_3(){ vector<Teacher *> v; Teacher t1(11, 22), t2(33, 44), t3(55, 66); v.push_back(&t1); v.push_back(&t2); v.push_back(&t3); vector<Teacher *>::iterator Start = v.begin(); while (Start != v.end()){ Teacher * pStart = *Start; cout << "ID:" << (*pStart).id << " Age:" << pStart->age << endl; Start++; } } int main(){ test_1(); test_2(); test_3(); return 0; }