2

【笔记】C++标准模版库

 2 years ago
source link: https://feiju12138.github.io/2022/09/02/C-%E6%A0%87%E5%87%86%E6%A8%A1%E7%89%88%E5%BA%93/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C++标准模版库(STL)学习笔记

STL基本概念

  • STL从广义上分为:容器、算法、迭代器
  • 容器算法之间通过迭代器进行无缝连接
  • STL几乎所有的代码都此用了类模版或者函数模版

STL6大组件

  • 容器:各种数据结构。如:vector、list、deque、set、map
    • 序列式容器:强调值的排序。序列式容器中的每个元素均有固定的位置
    • 关联式容器:二叉树结构。各元素之间没有严格的物理上的顺序关系
  • 算法:各种常用的算法。如:sort、find、copy、for_each
    • 质变算法:是指运算过程中会更改区间内的元素内容。例如:拷贝、替换、删除
    • 非质变算法:是指运算过程中不会更改区间内的元素内容。例如:查找、计数、遍历、寻找极值
  • 迭代器:扮演了容器与算法之间的胶合剂
    • 输入迭代器:对数据的只读访问,支持++==!=
    • 输出迭代器:对数据的只写访问,支持++
    • 前向迭代器:对数据的读写操作,并能向前推进迭代器,支持++==!=
    • 双向迭代器:对数据的读写操作,并能向前和向后操作,支持++--
    • 随机访问迭代器:对数据的读写操作,可以以跳跃的方式访问任意数据,支持++--[n]-n<<=>>=
  • 仿函数:行为类似函数,可作为算法的某种策略
  • 适配器:一种用来修饰容器或者仿函数或迭代器接口的东西
  • 空间配置器:负责空间的配置与管理

vector

  • 容器:vector
  • 算法:for_each
  • 迭代器:vector::iterator

包含头文件

#include <vector>

容器存放内置数据类型

// 定义容器
vector<int> v;

// 存放数据
v.push_back(1);

while遍历

// 起始迭代器,指向容器中第一个元素
vector<int>::iterator itBegin = v.begin();
// 结束迭代器,指向容器中最后一个元素的下一个位置
vector<int>::iterator itEnd = v.end();

while (itBegin != itEnd)
{
cout << *itBegin << endl;
itBegin++;
}

for遍历

for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << endl;
}

for_each遍历

  • 在for_each中传递回掉函数,实现遍历容器
#include <algorithm>

void print(int val)
{
cout << val << endl;
}

for_each(v.begin(), v.end(), print);

容器存放自定义数据类型

class Persion
{
int id;
};
Persion p;

// 定义容器
vector<Persion> v;

// 存放数据
v.push_back(p);

// 遍历
for (vector<Persion>::iterator it = v.begin(); it != v.end(); it++)
{
// 以对象的方式取值
cout << (*it).id << endl;
}

容器存放指针数据类型

class Persion
{
int id;
};
Persion p;

// 定义容器
vector<Persion*> v;

// 存放数据
v.push_back(&p);

// 遍历
for (vector<Persion*>::iterator it = v.begin(); it != v.end(); it++)
{
Persion *p = *it;
// 以指针的方式取值
cout << p->id << endl;
}
vector<vector<int>> father;

vector<int> son;
son.push_back(1);

father.pushback(son);

遍历所有数据

for (vector<vector<int>>::iterator fatherIt = father.begin(); it != father.end(); it++)
{
for (verctor<int>::iterator sonIt = (*fatherIt).begin(); sonIt != (*fatherIt).end(); sonIf++)
{
cout << *sonIt << " ";
}
cout << endl;
}

哔哩哔哩——黑马程序员


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK