C++ STL(标准模板库)是一套功能强大的c++模板类提供了通用的模板类和函数,这些模板类和函数可以实现多种流行和常用的算法和数据结构,如向量、链表、队列、栈。包含以下三个组成部分
组件 | 描述 |
---|---|
容器(Containers) | 容器是一个与数组类似的单元,用来存储值,且存储的值的类型相同;比如deque、list、vector、map等 |
算法(Algorithms) | 算法作用于容器,它们提供了执行各种操作的方法,包括对容器内容执行初始化、排序、搜索、转换等操作 |
迭代器(iterators) | 迭代用于遍历对象集合的元素,这些集合可能是容器,也可能是容器的子集 |
目录
零、 前言
1. 命名空间
当工程代码采用不同的程序和程序库时,针对不同的对象使用相同的标识符,就会出现名称冲突的现象,使用namespace就可以解决这个问题。标识符的可见范围namespace和class不同,namespace具有扩展开放性,可以出现在任意源码文件中。
C++ 标准程序库的所有标识符都被定义于一个名为std的namespace中,有以下三种方法使用:
- 直接指定标识符,例如
std::cout << std::hex << 3.4 << std::endl;
- 使用using declaration的方法,例如:
using std::cout;
using std::endl;
- 使用using directive,这是最简便的方法,就像被声明为全局标识符一样,但是由于某些重载的规格,这种方法可能导致意外地命名冲突,因此应避免使用第三种,除非程序很小为了方便。
using namespace std;
cout << hex << 3.4 << endl;
2. 通用工具
Pairs(对组)
class pair,凡需要将两个值视为一个单元的场景(例如必须返回两个值的某函数)就必须用到它,例如容器类别map和multimap,就是使用pairs来管理键值对元素
std::pair<int, float> p; // 初始化p.first 和 p.second为 0
std::pair<int, char *> p(42, "hello");
数值极限
标准库通过template numeric_limits提供极值,定义于,浮点数定义于
#include<iostream>
#include<string>
#include<limits> //头文件
using namespace std;
int main(){
cout<<"numeric_limits<unsigned short>::min()= "<<numeric_limits<unsigned short>::min()<<endl; //unsigned short的最小值
cout<<"numeric_limits<unsigned short>::max()= "<<numeric_limits<unsigned short>::max()<<endl; //unsigned short的最大值
cout<<"numeric_limits<int>::min()= "<<numeric_limits<int>::min()<<endl; //int的最小值
cout<<"numeric_limits<int>::max()= "<<numeric_limits<int>::max()<<endl; //int的最大值
cout<<"numeric_limits<short>::min()= "<<numeric_limits<short>::min()<<endl;
cout<<"numeric_limits<short>::max()= "<<numeric_limits<short>::max()<<endl;
cout<<"numeric_limits<double>::min()= "<<numeric_limits<double>::min()<<endl;
cout<<"numeric_limits<double>::lower()="<<numeric_limits<double>::lower()<<endl; //double最小值是lower,min只会返回e的负数次方
cout<<"numeric_limits<double>::max()= "<<numeric_limits<double>::max()<<endl;
cout<<"numeric_limits<int>::is_signed()= "<<numeric_limits<int>::is_signed<<endl;//是否有正负号
cout<<"numeric_limits<string>::is_specialized()= "<<numeric_limits<string>::is_specialized<<endl;//是否定义了数值极限
return 0;
}
辅助函数
定义在内的是哪个辅助函数,max()、min()、swap()。
namespace std {
template <class T>
inline const T& min(const T& a, const T& b) {
return b < a ? b : a;
}
template <class T>
inline const T& max(const T& a, const T& b) {
return a < b ? b : a;
}
template <class T>
inline void swap(T& a, T& b) {
T temp {a};
a = b;
b = temp;
}
}
非成员函数的方法
如果要为每一个容器类型,单独定义一个排序,查找的方法,则工作量会非常巨大,并且很多都是重复性的工作,因此STL定义了非成员函数,来完成通用的容器算法,如sort(),find(),swap().如果该容器类型vector.swap()存在,则代表要比普通的swap()函数效率更高.
- 1.遍历容器
for (vector<int>::iterator pr = test.begin(); pr != test.end(); pr++)
替换为:
for_each(test.begin(), test.end(), cout);
- 2.排序:
sort(test.begin(), test.end());
1> 如果要排序的对象是用户自己定义的,则需要重载比较操作符
struct Review {
string title;
int rating;
}
bool operator