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 }
打印:
使用 push_back 是值拷贝,也就是说会调用到拷贝构造函数。
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <string.h> 5 6 using namespace std; 7 8 class student 9 { 10 public: 11 student(int age, const char* name) 12 { 13 this->age = age; 14 strcpy_s(this->name, 64, name); 15 } 16 student(const student &s) 17 { 18 this->age = s.age; 19 strcpy_s(this->name, 64, s.name); 20 cout << "调用了拷贝构造函数" << endl; 21 } 22 private: 23 int age; 24 char name[64]; 25 }; 26 27 void demo() 28 { 29 vector<student> V; 30 31 student s1(18, "小美女"); 32 student s2(20, "大美女"); 33 34 V.push_back(s1); 35 V.push_back(s2); 36 37 cout << "V中的内用个数为:" << V.size() << endl; 38 39 } 40 41 int main() 42 { 43 demo(); 44 }
打印结果:
为了不影响性能,下面改用指针去执行 push_back,避免调用拷贝构造
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <string.h> 5 6 using namespace std; 7 8 class student 9 { 10 public: 11 student(int age, const char* name) 12 { 13 this->age = age; 14 strcpy_s(this->name, 64, name); 15 } 16 student(const student &s) 17 { 18 this->age = s.age; 19 strcpy_s(this->name, 64, s.name); 20 cout << "调用了拷贝构造函数" << endl; 21 } 22 public: 23 int age; 24 char name[64]; 25 }; 26 27 void demo() 28 { 29 vector<student *> V; 30 31 student s1(18, "小美女"); 32 student s2(20, "大美女"); 33 34 V.push_back(&s1); 35 V.push_back(&s2); 36 37 cout << "V中的内用个数为:" << V.size() << endl; 38 39 40 for (vector<student*>::iterator it = V.begin(); it != V.end(); it++) 41 { 42 cout << (**it).name << ":" << (**it).age << endl; 43 } 44 } 45 46 int main() 47 { 48 demo(); 49 }
执行结果:
===========================================================================================================================