STL
概述
为了避免从事大量重复工作,建立可重复性利用的东西,建立一套标准---STL(标准模板库)
分类
STL大体分为六大组件:容器、算法、迭代器、仿函数、适配器、空间配置器
- 容器:各种数据结构,如vector、list、deque、set、map等
- 算法:如sort、copy、find、for_each等
- 迭代器:容器和算法之间通过迭代器进行无缝衔接
- 仿函数:行为类似函数,可作为算法的某种策略
- 适配器(配接器):一种用来修饰容器/仿函数/迭代器接口的东西
- 空间配置器:负责空间的配置和管理
容器
vector 数组
如: 容器:vector 算法:for_each 迭代器: vector::iterator
#include <iostream>
#include <vector>
#include <algorithm> //STL 中标准算法头文件
using namespace std;
void test02(int val);
void test01()
{
//vector 数组内置数据结构
vector<int> v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
//遍历vector 容器中的数据
// vector<int>::iterator itBegin = v.begin(); //起始迭代器,指向容器第一个数据
// vector<int>::iterator itEnd = v.end(); //结束迭代器,指向容器中的最后一个数据的下一个位置
//遍历
//for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
//{
// //取值打印
// cout << *it << endl;
//}
// 使用STL提供的遍历算法 ,需要引入算法头文件
for_each(v.begin(), v.end(), test02);
}
void test02(int val)
{
cout << val << endl;
}
string
string 本质是一个类,是C++类型的字符串。
string 和 char* 区别:
char* 是一个指针(const char* str :c语言风格字符串 ) string 是一个类,类内部封装了char*
string类型的数据输出,必须包含string的头文件
string 赋值操作
- =
- str.assign("hello") 将s内容赋值给str
- str.assign(const char*s, int n) 将s的前n个字符赋值给当前字符串
string 字符串拼接
实现字符串末尾拼接字符串
- +=
- str1.append(str2) 把str2连接到当前字符串末尾
- str1.append(str2, int n) 将str2的前n个字符连接到当前字符串末尾
- str1.append(str2, int pos, int n) 将str2中从第pos开始的n个字符连接到字符串末尾