STL(标准模板库)

STL 主要分为三类:

  • container(容器)  -  用来管理一组数据元素
  • lterator(迭代器)  -  可遍历STL容器内全部或部分元素的对象
  • algorithm(算法)  -  对数据进行处理(解决问题)步骤的有限集合。

容器和算法通过迭代器可以进行无缝连接,在STL中几乎所有的代码都采用了模板类和模板函数的方式,这相比于传统的由函数和类组成库来说提供了更好的代码重用机会。

STL最早源于惠普收益延时,早于C++存在,但是C++引入STL概念后,STL就成为C++的一部分,因为它被内建在你的编译器之内,不需要另行安装。

STL被组织为下面的13个头文件:<algorithm>、<deque>、<functional>、<iterator>、<vector>、<list>、<map>、<memory>、<numeric>、<queue>、<set>、<stack>、<utility>

下面代码简单说明STL中的一些功能:

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     //第一部分:容器 vector
10     vector<int>num;
11 
12     num.push_back(1);    //push_back:往 vector 最后放置1个元素 “1”
13     num.push_back(2);
14     num.push_back(3);
15     num.push_back(4);
16     num.push_back(3);
17 
18     cout << "num 的元素个数:" << num.size() << endl;
19 
20     //第二部分:迭代器 begin() end()
21     cout << "num 中保存的元素:";
22     for (vector<int>::iterator it = num.begin(); it != num.end(); it++)    //用迭代器来遍历,使用指针 it, 从 begin()开始,it++ 至 end()
23     {
24         cout << *it << " ";
25     }
26 
27     //第三部分:算法 count
28     int numCount = count(num.begin(), num.end(), 3);
29 
30     cout << "\nnum 中数值为3的元素个数为:"<< numCount << endl;
31 
32     return 0;
33 }

打印:

===========================================================================================================================

猜你喜欢

转载自www.cnblogs.com/CooCoChoco/p/12650606.html