一、泛型程式設計
1、如果說面向對象是一種通過間接層來調用函數,以換取一種抽象,那麼泛型程式設計則是更直接的抽象,他不會因為間接層而損失效率;
不同于面向對象的動态期多态,泛型程式設計是一種靜态器多态,通過編譯器生成最直接的代碼;
泛型程式設計可以将算法與特定類型、結構剝離,盡可能複用代碼。
2、例子
template<int n>
struct Sum
{
enum Value{N = Sum<n-1>::N+n};
};
template<>
struct Sum<1>
{
enum Value{N = 1};
};
int main()
{
cout << Sum<100>::N << endl;
return 0;
}
二、STL(Standard Template Library)
1、STL算法是泛型的,不與任何特定資料結構和對象綁定,不必在環境類似的情況下重寫代碼;
STL算法可以量身定做,并且具有很高的效率;
STL可以進行擴充,可以編寫自己的元件并且能與STL标準的元件進行很好的
2、總體
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsISPrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdsATOfd3bkFGazxCMx8VesATMfhHLlN3XnxCMwEzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5yNkZzM4QGMiRTYzgzNwYTY5QmMxYmNzkDO5YzNmJjZ08CXwMzLclDMxIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLzM3Lc9CX6MHc0RHaiojIsJye.png)
3、1)序列式容器(其中元素是可排序的;vector list deque;而stack queue priority_queue是容器擴充卡)
struct Display
{
void operator()(int i)
{
cout << i << " ";
}
};
........
int iArr[] = { 1,2,3,4,5 };
vector<int>iVector(iArr, iArr + 4);
for_each(iVector.begin(), iVector.end(), Display());
2)關聯式容器(每個資料元素都是由一個鍵key和值value組成,當元素被插入到容器時,按其鍵以某種特定規則放入适當位置;set multiset map multimap)
//c++一般實作
bool MySort(int a, int b)
{
return a < b;
}
void Display(int a)
{
cout << a << " ";
}
//c++泛型實作
template<typename T>
bool MySortT(T const& a, T const& b)
{
return a < b;
}
template<typename T>
inline void DisplayT(T const& a)
{
cout << a << " ";
}
//c++仿函數實作
struct SortF
{
bool operator()(int a, int b)
{
return a < b;
}
};
struct DisplayF
{
void operator()(int a) {
cout << a << " ";
}
};
//c++仿函數模闆實作
template<typename T>
struct SortFT
{
inline bool operator()(T const& a, T const& b) const
{
return a < b;
}
};
template<typename T>
struct DisplayFT
{
inline void operator()(T const& a) const
{
cout << a << " ";
}
};
int main()
{
//c++一般方式
int arr1[] = { 4,1,3,2,7 };
sort(arr1, arr1 + 5, MySort);
for_each(arr1, arr1 + 5, Display);
cout << endl;
//c++泛型
int arr2[] = { 4,1,3,2,7 };
sort(arr2, arr2 + 5, MySortT<int>);
for_each(arr2, arr2 + 5, DisplayT<int>);
cout << endl;
//c++仿函數
int arr3[] = { 4,1,3,2,7 };
sort(arr3, arr3 + 5, SortF());
for_each(arr3, arr3 + 5, DisplayF());
cout << endl;
//c++仿函數末模闆
int arr4[] = { 4,1,3,2,7 };
sort(arr4, arr4 + 5, SortFT<int>());
for_each(arr4, arr4 + 5, DisplayFT<int>());
cout << endl;
return 0;
}