基本概念
STL(標準模板庫)
STL從廣義上分爲:容器、算法、迭代器,容器和算法之間通過迭代器進行無縫鏈接。
STL六大組件:容器、算法、迭代器、仿函數、適配器、空間配置器
容器:各種數據結構(類模板)
算法:各種常用的算法(函數模板)
迭代器:所有的容器都有自己的迭代器
容器
序列式容器
關聯式容器
算法
質變算法:運算過程中改變區間內的元素的內容,例如拷貝,替換,刪除等
非質變算法:運算過程中不會改變區間內的元素的內容,例如查找、計數、遍歷等
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
void MyPrint(int val)
{
cout << val << endl;
}
// 普通指針也是屬於一種迭代器
void test01()
{
int arr[5] = { 1,2,3,4,5 };
int *p = arr;
for (int i = 0; i < 5; i++)
{
// cout << arr[i] << endl;
cout << *p++ << endl;
}
}
void test02()
{
vector<int>v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
// 遍歷1
/*vector<int>::iterator itBegin = v.begin();
vector<int>::iterator itEnd = v.end(); // 指向最後一個元素的下一個位置
while (itBegin != itEnd)
{
cout << *itBegin << endl;
itBegin++;
}*/
// 遍歷2
/*for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << endl;
}*/
// 遍歷3
for_each(v.begin(), v.end(), MyPrint);
}
// 自定義數據類型
class Person
{
public:
Person(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
string m_name;
int m_age;
};
void test03()
{
/*vector<Person>v;
Person p1("aaaa", 10);
Person p2("bbbb", 20);
Person p3("cccc", 30);
Person p4("dddd", 40);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
// 遍歷
for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
{
cout << (*it).m_name;
cout << it->m_age << endl;
}*/
vector<Person *>v;
Person p1("aaaa", 10);
Person p2("bbbb", 20);
Person p3("cccc", 30);
Person p4("dddd", 40);
v.push_back(&p1);
v.push_back(&p2);
v.push_back(&p3);
v.push_back(&p4);
// 遍歷
for (vector<Person *>::iterator it = v.begin(); it != v.end(); it++)
{
cout << (**it).m_name;
cout << (*it)->m_age << endl;
}
}
int main()
{
// test02();
test03();
system("pause");
return 0;
}