生活随笔
收集整理的這篇文章主要介紹了
###STL学习--标准模板库
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
下面進行STL的學習。希望能了解標準模板庫中的常用容器,迭代器,可以自由運用STL以提高編寫代碼的效率。下面的內容我想以知識點為總結,不再像《Effective C++》那樣以章節進行總結,這樣寫可能毫無組織,但可以看到整個學習的歷程。點擊查看Evernote原文。
#@author: gr
#@date: 2014-07-18
#@email: forgerui@gmail.com
### 一、Contents
C++模板 template<typename T1, typename T2>class Test{//下面的函數使用了T1,T2模板int count(T1 x, T2 y){return x.num + y.num; }}; //使用傳進來的str構造一個容器類Container
template<typename Container>
T make(string str){return Container(str.begin(), str.end());
}
//-----------------------------------------------
//make函數的使用vector, list, deque...
vector<char> vStr = make<vector<char>>("hello");
list<char> lStr = make<list<char>>("hello");
deque<char> dStr = make<deque<char>>("hello");
// ... - 成員函數模板(在類模板中,還可以使用成員函數模板,兩者不受影響)
template<typename T1, typename T2>class Test{//下面的函數使用了T1,T2模板int count(T1 x, T2 y){return x.num + y.num; }template<typename T>void show(T x){std::cout<<x.num<<endl;}};默認模板參數 template<typename T, typename Allocator = allocator<T> >class vector{// ...}
通過allocator<T>為第2個模板參數Allocator賦一個初值,allocator類型(用戶自己定義的一個類)則在未提供第二個模板時使用。這樣,vector<int>和vector<int, allocator<int>都是可以的。
容器 - 序列容器
- vector<T>:提供對變長序列的隨機訪問
- deque<T>:提供對變長序列的隨機訪問
- list<T>:提供對變長序列的線性時間訪問O(N),其中N是序列的當前長度。
- 順序關聯容器
- set<Key> 惟一的鍵
- multi<Key> 可重復的鍵
- map<Key, T> 惟一的鍵索引類型T
- multimap<Key, T> 可重復的鍵索引類型T
#include<map>using namespace std;int main(){map<string, long>directory;directory["A"] = 1;directory["B"] = 2;directory["C"] = 3;string name = "B";//查找namemap<string, long>::iterator it = directory.find(name);if (it != directory.end())cout<<"find the str, value is "<<*it<<endl;}類屬算法 //1. reverse: 逆序reverse(vector.begin(), vector.end()); //2. find: 在序列中查找特定值'e'string::iterator it = find(str.begin(), str.end(), 'e');//map中的findmap<Key, T>::iterator it = _map.find(key); //3. merge: 將兩個容器中的東西拷貝到一個容器中/*** @func: merge* @params: first1, last1分別表示輸入序列的起始和終止位置* @params: first2, last2分別表示另一個輸入序列的起始和終止位置* @params: result表示合并后序列存放的位置* @example: 合并string與list到deque* merge(str, str+strlen(str), list1.begin(), list1.end(), deque1.begin());* merge(str.begin(), str.end(), list1.begin(), list1.end(), deque1.begin());* * @comments: !!!注意,這里的兩個輸入都必須是升序排列的,否則報錯*/merge(first1, last1, first2, last2, result);//4. replace: 替換其中的值replace(a.begin(), a.end(), 'a', 'b');//5. copy: 拷貝一段東西到另一個容器中copy(a.begin(), a.end(), b.begin());
迭代器- 輸入迭代器
- 輸出迭代器
- 前向迭代器
- 雙向迭代器
- 隨機訪問迭代器
- 插入迭代器
- back_insert_iterator
- front_insert_iterator
- insert_iterator
- 流迭代器
- istream_iterator
- ostream_iterator
函數對象
適配器
分配器
### 二、References
迭代器和類屬算法介紹
轉載于:https://www.cnblogs.com/gr-nick/p/3880243.html
總結
以上是生活随笔為你收集整理的###STL学习--标准模板库的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。