GeekBand極客班STL與泛型編程第一周筆記

c++標準庫體系結構與內核分析

第一講:示范運用STL各大部件 (components),并初步認識其體系結構

1.認識headers、版本、重要資源

所謂generic programing,GP泛型編程,就是使用template模板為主要工具來編寫程序
根據源代碼分析c++STL之體系結構
應具備的基礎:c++基本語法,包括如何正確使用模板templates
-level0:使用c++標準庫
-level1:深入認識c++標準庫,清楚其在內存中的結構等
-level2:良好使用c++標準庫
-level3:擴充c++標準庫
c++標準庫與STL
-c++ standard library:目前c++中已給的頭文件
-standard template library:標準模板庫,分為六大部件,標準庫中大量存在STL
-標準庫以Header files形式呈現,所以源代碼可見
-headers中的組件封裝于namespace std
using namespace std;
using std::cout;

#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;

不同版本標準庫的用法基本相同
推薦網站:
-www.cplusplus.com
-en.cppreference.com
-gcc.gnu.org

2.STL體系結構基礎介紹

STL六大部件:
-容器containers
-分配器allocators
-算法algorithms
-迭代器iterators
-適配器adapters
-仿函式functors
分配器用來支持容器存放
部分操作在容器本身操作另外部分放在算法操作
面向對象編程中鼓勵將數據及函數放在類中,與STL不同
容器用來存放要處理的數據,算法對容器中的數據進行處理
迭代器是數據與操作的橋梁,是一種泛化的指針
仿函數作用像函數一樣
適配器用來幫助轉換,迭代器適配、仿函數適配、容器適配

#include <vector>        //需要使用容器要引入對應的頭文件
#include <algorithm>
#include <functional>
#include <iostream>

using namespace std;

int main()
{
    int ia[6]={27,210,12,47,109,83};
    vector<int,allocator<int>> vi(ia,ia+6);
//容器↑       分配器↑
//模板:尖括號中第一個參數為類型,第二個參數允許放一個分配器幫助分配內存,不寫的話使用默認
    cout<<count_if(vi.begin(),vi.end,not1(bind2nd(less<int>(),40)));   
//      算法↑ 迭代器↑           適配器↑       
//對數據的操作:需要用適配器來做容器和算法的接口
//predicate
    return 0;
}

復雜度complexity
-O(1)、O(c):常數時間 constant time
-O(n):線性時間 linear time
-O(log2n):次線性實踐 sub-linear time
-O(n^2):平方時間 quadratic time
-O(n^3):立方時間 cubic time
-O(2^n):指數時間 exponential time
-O(nlog2n):介于線性及二次方成長的中間
“前閉后開”區間
標準庫規定,容器中頭指針指向第一個元素,尾指針所指為容器最后元素的下一個位置
容器中的空間并不一定連續,也可能是鏈表或者哈希表


Container<T> c;
...
Container<T>::iterator ite = c.begin();
//容器都有其專屬的一個iterator,用其類型聲明頭指針
for(;ite!=c.end();ite++)
...
//對容器進行遍歷

c++11新功能:
-對容器進行遍歷
range-based "for" statement (since C++11)
for(decl:coll){statement}

for(int i : {2,3,5,7,9,13,17,19})
{
    std::cout<<i<<std::endl;
}
std::vector<double> vec;
for(auto elem : vec)
{
    std::cout<<elem<<std::endl;
}
for(auto& elem : vec)
{
    elem *= 3;
}

-auto keyword

list<string> c;
...
list<string>::iterator ite;
ite=::find(c.begin(),c.end(),/*target*/);

list<string> c;
...
auto ite = ::find(c.begin(),c.end(),/*target*/);

3.容器之分類與各種測試

容器-結構

-順序表
-鏈表
-樹
-堆
-哈希表

容器-分類

sequence containers
associative containers
unordered containers
hash table separate chaining
-array,固定大小,不可擴充
-vector,開頭固定,尾可擴充
-list,雙鏈表,雙向都有指針
-forward_list,單鏈表,指針為單向
-slist
-deque,頭尾可擴充
-stack
-multiset,集合中元素可重復
-multimap
-unordered_multiset,分散無序存放,
-unordered_multimap
-set,集合,一種平衡二叉樹,每個元素中key和value為同一個,集合中元素不可重復
-map,圖,通常用紅黑樹,每個元素中key和value為不同變量
-unordered_set
-unordered_map
-hash_set,哈希結構,目前最優
-hash_multiset
-hash_multimap


四個函數
-輸入一個target
-輸入一個字符串target
-比較兩個long型大小
-比較兩個字符串大小

使用容器array

#include <array>
#include <iostream>
#include <ctime> 
#include <cstdlib> //qsort, bsearch, NULL

namespace jj01
{
void test_array()
{
    cout << "\ntest_array().......... \n";
     
array<long,ASIZE> c;    
            
clock_t timeStart = clock();                                    
    for(long i=0; i< ASIZE; ++i) {
        c[i] = rand(); 
    }
    cout << "milli-seconds : " << (clock()-timeStart) << endl;  //
    cout << "array.size()= " << c.size() << endl;       
    cout << "array.front()= " << c.front() << endl; 
    cout << "array.back()= " << c.back() << endl;   
    cout << "array.data()= " << c.data() << endl;   
    
long target = get_a_target_long();

    timeStart = clock();
    ::qsort(c.data(), ASIZE, sizeof(long), compareLongs);
long* pItem = (long*)::bsearch(&target, (c.data()), ASIZE, sizeof(long), compareLongs); 
    cout << "qsort()+bsearch(), milli-seconds : " << (clock()-timeStart) << endl;   //    
    if (pItem != NULL)
        cout << "found, " << *pItem << endl;
    else
        cout << "not found! " << endl;  
}
}

array
-尖括號中第一個參數為類型,第二個參數為容器大小

使用容器vector

#include <vector>
#include <stdexcept>
#include <string>
#include <cstdlib> //abort()
#include <cstdio>  //snprintf()
#include <iostream>
#include <ctime> 
#include <algorithm>    //sort()
namespace jj02
{
void test_vector(long& value)
{
    cout << "\ntest_vector().......... \n";
     
vector<string> c;   
char buf[10];
            
clock_t timeStart = clock();                                
    for(long i=0; i< value; ++i)
    {
        try {
            snprintf(buf, 10, "%d", rand());
            c.push_back(string(buf));           
        }
        catch(exception& p) {
            cout << "i=" << i << " " << p.what() << endl;   
                 //曾經最高 i=58389486 then std::bad_alloc
            abort();
        }
    }
    cout << "milli-seconds : " << (clock()-timeStart) << endl;  
    cout << "vector.max_size()= " << c.max_size() << endl;  //1073747823
    cout << "vector.size()= " << c.size() << endl;      
    cout << "vector.front()= " << c.front() << endl;    
    cout << "vector.back()= " << c.back() << endl;  
    cout << "vector.data()= " << c.data() << endl;
    cout << "vector.capacity()= " << c.capacity() << endl << endl;      

                                                                                
string target = get_a_target_string();
    {
    timeStart = clock();
auto pItem = find(c.begin(), c.end(), target);
    cout << "std::find(), milli-seconds : " << (clock()-timeStart) << endl;  
     
    if (pItem != c.end())
        cout << "found, " << *pItem << endl << endl;
    else
        cout << "not found! " << endl << endl;
    }

    {
    timeStart = clock();
    sort(c.begin(), c.end());
    cout << "sort(), milli-seconds : " << (clock()-timeStart) << endl; 
    
    timeStart = clock();        
string* pItem = (string*)::bsearch(&target, (c.data()), 
                                   c.size(), sizeof(string), compareStrings); 
    cout << "bsearch(), milli-seconds : " << (clock()-timeStart) << endl; 
       
    if (pItem != NULL)
        cout << "found, " << *pItem << endl << endl;
    else
        cout << "not found! " << endl << endl;  
    }
    
    c.clear();
    test_moveable(vector<MyString>(),vector<MyStrNoMove>(), value); 
}   
}

-tips:測試程序的每一段歸在一個namespace中
vector
-尖括號中的參數為類型

使用容器list

#include <list>
#include <stdexcept>
#include <string>
#include <cstdlib> //abort()
#include <cstdio>  //snprintf()
#include <algorithm> //find()
#include <iostream>
#include <ctime> 
namespace jj03
{
void test_list(long& value)
{
    cout << "\ntest_list().......... \n";
     
list<string> c;     
char buf[10];
            
clock_t timeStart = clock();                            
    for(long i=0; i< value; ++i)
    {
        try {
            snprintf(buf, 10, "%d", rand());
            c.push_back(string(buf));       
        }
        catch(exception& p) {
            cout << "i=" << i << " " << p.what() << endl;   
            abort();
        }
    }
    cout << "milli-seconds : " << (clock()-timeStart) << endl;      
    cout << "list.size()= " << c.size() << endl;
    cout << "list.max_size()= " << c.max_size() << endl;    //357913941
    cout << "list.front()= " << c.front() << endl;  
    cout << "list.back()= " << c.back() << endl;        
        
string target = get_a_target_string();      
    timeStart = clock();        
auto pItem = find(c.begin(), c.end(), target);                      
    cout << "std::find(), milli-seconds : " << (clock()-timeStart) << endl;     
    
    if (pItem != c.end())
        cout << "found, " << *pItem << endl;
    else
        cout << "not found! " << endl;  
        
    timeStart = clock();        
    c.sort();                       
    cout << "c.sort(), milli-seconds : " << (clock()-timeStart) << endl;                
        
    c.clear();
    test_moveable(list<MyString>(),list<MyStrNoMove>(), value);                             
}   
}

list
-尖括號參數為類型
循環存入數據

4.分配器之測試

使用分配器allocator

不同容器在聲明時候的分配方式
-尖括號第二位置的參數即是所選用的分配器

#include <list>
#include <stdexcept>
#include <string>
#include <cstdlib>      //abort()
#include <cstdio>       //snprintf()
#include <algorithm>    //find()
#include <iostream>
#include <ctime> 

#include <cstddef>
#include <memory>   //內含 std::allocator  
    //欲使用 std::allocator 以外的 allocator, 得自行 #include <ext\...> 
#ifdef __GNUC__     
#include <ext\array_allocator.h>
#include <ext\mt_allocator.h>
#include <ext\debug_allocator.h>
#include <ext\pool_allocator.h>
#include <ext\bitmap_allocator.h>
#include <ext\malloc_allocator.h>
#include <ext\new_allocator.h>  
#endif

namespace jj20
{
//pass A object to function template impl(),
//而 A 本身是個 class template, 帶有 type parameter T,  
//那麼有無可能在 impl() 中抓出 T, 創建一個 list<T, A<T>> object? 
//以下先暫時迴避上述疑問.
    
void test_list_with_special_allocator()
{
#ifdef __GNUC__ 
    cout << "\ntest_list_with_special_allocator().......... \n";
     
    //不能在 switch case 中宣告,只好下面這樣.               //1000000次 
    list<string, allocator<string>> c1;                     //3140
    list<string, __gnu_cxx::malloc_allocator<string>> c2;   //3110
    list<string, __gnu_cxx::new_allocator<string>> c3;      //3156
    list<string, __gnu_cxx::__pool_alloc<string>> c4;       //4922
    list<string, __gnu_cxx::__mt_alloc<string>> c5;         //3297
    list<string, __gnu_cxx::bitmap_allocator<string>> c6;   //4781                                                      
     
int choice;
long value;     

    cout << "select: "
         << " (1) std::allocator "
         << " (2) malloc_allocator "
         << " (3) new_allocator "
         << " (4) __pool_alloc "
         << " (5) __mt_alloc "
         << " (6) bitmap_allocator ";
    
    cin >> choice;
    if ( choice != 0 ) {
        cout << "how many elements: ";
        cin >> value;       
    }
            
char buf[10];           
clock_t timeStart = clock();                                
    for(long i=0; i< value; ++i)
    {
        try {
            snprintf(buf, 10, "%d", i);
            switch (choice) 
            {
                case 1 :    c1.push_back(string(buf));  
                            break;
                case 2 :    c2.push_back(string(buf));  
                            break;      
                case 3 :    c3.push_back(string(buf)); 
                            break;      
                case 4 :    c4.push_back(string(buf));  
                            break;      
                case 5 :    c5.push_back(string(buf));      
                            break;      
                case 6 :    c6.push_back(string(buf));  
                            break;              
                default: 
                    break;      
            }                   
        }
        catch(exception& p) {
            cout << "i=" << i << " " << p.what() << endl;   
            abort();
        }
    }
    cout << "a lot of push_back(), milli-seconds : " << (clock()-timeStart) << endl;    
    
     
    //test all allocators' allocate() & deallocate();
    int* p;     
    allocator<int> alloc1;  
    p = alloc1.allocate(1);  
    alloc1.deallocate(p,1);     
                        
    __gnu_cxx::malloc_allocator<int> alloc2;  
    p = alloc2.allocate(1);  
    alloc2.deallocate(p,1);     
        
    __gnu_cxx::new_allocator<int> alloc3;   
    p = alloc3.allocate(1);  
    alloc3.deallocate(p,1);     
        
    __gnu_cxx::__pool_alloc<int> alloc4;    
    p = alloc4.allocate(2);  
    alloc4.deallocate(p,2);     //我刻意令參數為 2, 但這有何意義!! 一次要 2 個 ints? 
        
    __gnu_cxx::__mt_alloc<int> alloc5;  
    p = alloc5.allocate(1);  
    alloc5.deallocate(p,1);     
            
    __gnu_cxx::bitmap_allocator<int> alloc6;    
    p = alloc6.allocate(3);  
    alloc6.deallocate(p,3);     //我刻意令參數為 3, 但這有何意義!! 一次要 3 個 ints? 
#endif          
}                                                           
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,825評論 6 546
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,814評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,980評論 0 384
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 64,064評論 1 319
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,779評論 6 414
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,109評論 1 330
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,099評論 3 450
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,287評論 0 291
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,799評論 1 338
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,515評論 3 361
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,750評論 1 375
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,221評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,933評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,327評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,667評論 1 296
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,492評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,703評論 2 380

推薦閱讀更多精彩內容