STL學習筆記-入門概念
1. 入門概念
STL最大的特點: 實現了算法和數據結構的有效分離
STL主要內容:算法(algorithm)、容器(container)、迭代器(iterator)
容器 -> 提供數據結構
算法 -> 按照實際問題,對數據進行處理
迭代器 -> 使得容器和算法進行無縫對接
實例感受:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Student{
public:
int age;
char name[64];
void printStuInfo() {
cout << "age : " << age << endl;
}
};
void main() {
//容器:將元素拷入到容器中
vector<int> v;
v.push_back(-1);
v.push_back(1);
v.push_back(2);
v.push_back(1);
//迭代器:相當於一個指針,能訪問容器中的數據
for(vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
//算法: 統計容器中1的個數, 算法和迭代器能進行無縫的連接
int num = count(v.begin(), v.end(), 1);
cout << " num of 1 : " << num << endl;
//容器不僅可以裝基本數據類型,還可以裝複雜數據類型
Student s1, s2, s3;
s1.age = 18;
s2.age = 19;
s3.age = 20;
vector<Student *> stu;
stu.push_back(&s1);
stu.push_back(&s2);
stu.push_back(&s3);
for(vector<Student *>::iterator it = stu.begin(); it != stu.end(); it++) {
cout << (*it)->age << endl; // *it 纔是 Student * 類型的
}
}
容器簡介:
容器的分類:
序列式容器:每個元素位置固定,取決於插入的時機,與元素值無關。
如vector、deque、list、quene、stack、priority_quene
關聯式容器:元素位置取決於特定的排序準則,和插入順序無關。
如set、multiset、map、multimap
容器中的元素是按照值賦值的方式進行的,因此容器類模板的類型必須提供拷貝構造函數
容器不僅可以裝基本數據類型,還可以裝複雜數據類型
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.