c++ list, vector, map, set 區別與用法比較

List封裝了鏈表,Vector封裝了數組, list和vector得最主要的區別在於vector使用連續內存存儲的,他支持[]運算符,而list是以鏈表形式實現的,不支持[]。html

Vector對於隨機訪問的速度很快,可是對於插入尤爲是在頭部插入元素速度很慢,在尾部插入速度很快。List對於隨機訪問速度慢得多,由於可能要遍歷整個鏈表才能作到,可是對於插入就快的多了,不須要拷貝和移動數據,只須要改變指針的指向就能夠了。另外對於新添加的元素,Vector有一套算法,而List能夠任意加入。
Map,Set屬於標準關聯容器,使用了很是高效的平衡檢索二叉樹:紅黑樹,他的插入刪除效率比其餘序列容器高是由於不須要作內存拷貝和內存移動,而直接替換指向節點的指針便可。
Set和Vector的區別在於Set不包含重複的數據。Set和Map的區別在於Set只含有Key,而Map有一個Key和Key所對應的Value兩個元素。
Map和Hash_Map的區別是Hash_Map使用了Hash算法來加快查找過程,可是須要更多的內存來存放這些Hash桶元素,所以能夠算得上是採用空間來換取時間策略。ios

 

 

 

vector算法

    向量 至關於一個數組
    在內存中分配一塊連續的內存空間進行存儲。支持不指定vector大小的存儲。STL內部實現時,首先分配一個很是大的內存空間預備進行存儲,即capacituy()函數返回的大小,當超過此分配的空間時再總體從新放分配一塊內存存儲,這給人以vector能夠不指定vector即一個連續內存的大小的感受。一般此默認的內存分配能完成大部分狀況下的存儲。
   優勢:(1) 不指定一塊內存大小的數組的連續存儲,便可以像數組同樣操做,但能夠對此數組
               進行動態操做。一般體如今push_back() pop_back()
               (2) 隨機訪問方便,即支持[ ]操做符和vector.at()
               (3) 節省空間。
   缺點:(1) 在內部進行插入刪除操做效率低。
               (2) 只能在 vector的最後進行push和pop,不能在vector的頭進行push和pop。
               (3) 當動態添加的數據超過vector默認分配的大小時要進行總體的從新分配、拷貝與釋
                     放 

list
    雙向鏈表
    每個結點都包括一個信息快Info、一個前驅指針Pre、一個後驅指針Post。能夠不分配必須的內存大小方便的進行添加和刪除操做。使用的是非連續的內存空間進行存儲。
   優勢:(1) 不使用連續內存完成動態操做。
               (2) 在內部方便的進行插入和刪除操做
               (3) 可在兩端進行push、pop
   缺點:(1) 不能進行內部的隨機訪問,即不支持[ ]操做符和vector.at()
               (2) 相對於verctor佔用內存多

deque
   雙端隊列 double-end queue
   deque是在功能上合併了vector和list。
   優勢:(1) 隨機訪問方便,即支持[ ]操做符和vector.at()
               (2) 在內部方便的進行插入和刪除操做
               (3) 可在兩端進行push、pop
   缺點:(1) 佔用內存多

使用區別:

     1 若是你須要高效的隨即存取,而不在意插入和刪除的效率,使用vector 
     2 若是你須要大量的插入和刪除,而不關心隨即存取,則應使用list 
     3 若是你須要隨即存取,並且關心兩端數據的插入和刪除,則應使用deque
 
 
 
 
 
 
C++STL中vector容器的用法 
 
http://xiamaogeng.blog.163.com/blog/static/1670023742010102494039234/
 
vector是C++標準模板庫 中的部份內容,它是一個多功能的,可以操做多種數據結構和算法的模板類和函數庫。vector之因此被認爲是一個容器,是由於它可以像容器同樣存放各類類型的對象,簡單地說vector是一個可以存聽任意類型的動態數組,可以增長和壓縮數據。爲了可使用vector,必須在你的頭文件中包含下面的代碼:

#include <vector>編程

vector屬於std命名域的,所以須要經過命名限定,以下完成你的代碼:後端

using std::vector;     vector<int> v;數組

或者連在一塊兒,使用全名:數據結構

std::vector<int> v;less

建議使用全局的命名域方式:數據結構和算法

using namespace std;函數

1.vector的聲明

   vector<ElemType> c;   建立一個空的vector

   vector<ElemType> c1(c2); 建立一個vector c1,並用c2去初始化c1

   vector<ElemType> c(n) ; 建立一個含有n個ElemType類型數據的vector;

   vector<ElemType> c(n,elem); 建立一個含有n個ElemType類型數據的vector,並所有初始化爲elem;

   c.~vector<ElemType>(); 銷燬全部數據,釋放資源;

2.vector容器中經常使用的函數。(c爲一個容器對象)

    c.push_back(elem);   在容器最後位置添加一個元素elem

    c.pop_back();            刪除容器最後位置處的元素

    c.at(index);                返回指定index位置處的元素

    c.begin();                   返回指向容器最開始位置數據的指針

    c.end();                      返回指向容器最後一個數據單元的指針+1

    c.front();                     返回容器最開始單元數據的引用

    c.back();                     返回容器最後一個數據的引用

    c.max_size();              返回容器的最大容量

    c.size();                      返回當前容器中實際存放元素的個數

    c.capacity();               同c.size()

     c.resize();                   從新設置vector的容量

    c.reserve();                同c.resize()

    c.erase(p);               刪除指針p指向位置的數據,返回下指向下一個數據位置的指針(迭代器)

    c.erase(begin,end)     刪除begin,end區間的數據,返回指向下一個數據位置的指針(迭代器)

    c.clear();                    清除全部數據

    c.rbegin();                  將vector反轉後的開始指針返回(其實就是原來的end-1)

    c.rend();                     將vector反轉後的結束指針返回(其實就是原來的begin-1)

    c.empty();                   判斷容器是否爲空,若爲空返回true,不然返回false

    c1.swap(c2);               交換兩個容器中的數據

    c.insert(p,elem);          在指針p指向的位置插入數據elem,返回指向elem位置的指針       

    c.insert(p,n,elem);      在位置p插入n個elem數據,無返回值

    c.insert(p,begin,end) 在位置p插入在區間[begin,end)的數據,無返回值

3.vector中的操做

    operator[] 如: c.[i];

    同at()函數的做用相同,即取容器中的數據。

在上大體講述了vector類中所含有的函數和操做,下面繼續討論如何使用vector容器;

1.數據的輸入和刪除。push_back()與pop_back()


2.元素的訪問


3.排序和查詢

4.二維容器

C++ STLList隊列用法(實例)

http://www.cnblogs.com/madlas/articles/1364503.html
 
C++ STL List隊列用法(實例)
2007-12-15 12:54

#include <iostream>
#include <list>
#include <numeric>
#include <algorithm>

using namespace std;

//建立一個list容器的實例LISTINT
typedef list<int> LISTINT;

//建立一個list容器的實例LISTCHAR
typedef list<char> LISTCHAR;

void main(void)
{
    //--------------------------
    //用list容器處理整型數據
    //--------------------------
    //用LISTINT建立一個名爲listOne的list對象
    LISTINT listOne;
    //聲明i爲迭代器
    LISTINT::iterator i;

    //從前面向listOne容器中添加數據
    listOne.push_front (2);
    listOne.push_front (1);

    //從後面向listOne容器中添加數據
    listOne.push_back (3);
    listOne.push_back (4);

    //從前向後顯示listOne中的數據
    cout<<"listOne.begin()--- listOne.end():"<<endl;
    for (i = listOne.begin(); i != listOne.end(); ++i)
        cout << *i << " ";
    cout << endl;

    //從後向後顯示listOne中的數據
LISTINT::reverse_iterator ir;
    cout<<"listOne.rbegin()---listOne.rend():"<<endl;
    for (ir =listOne.rbegin(); ir!=listOne.rend();ir++) {
        cout << *ir << " ";
    }
    cout << endl;

    //使用STL的accumulate(累加)算法
    int result = accumulate(listOne.begin(), listOne.end(),0);
    cout<<"Sum="<<result<<endl;
    cout<<"------------------"<<endl;

    //--------------------------
    //用list容器處理字符型數據
    //--------------------------

    //用LISTCHAR建立一個名爲listOne的list對象
    LISTCHAR listTwo;
    //聲明i爲迭代器
    LISTCHAR::iterator j;

    //從前面向listTwo容器中添加數據
    listTwo.push_front ('A');
    listTwo.push_front ('B');

    //從後面向listTwo容器中添加數據
    listTwo.push_back ('x');
    listTwo.push_back ('y');

    //從前向後顯示listTwo中的數據
    cout<<"listTwo.begin()---listTwo.end():"<<endl;
    for (j = listTwo.begin(); j != listTwo.end(); ++j)
        cout << char(*j) << " ";
    cout << endl;

    //使用STL的max_element算法求listTwo中的最大元素並顯示
    j=max_element(listTwo.begin(),listTwo.end());
    cout << "The maximum element in listTwo is: "<<char(*j)<<endl;
}

#include <iostream>
#include <list>

using namespace std;
typedef list<int> INTLIST;

//從前向後顯示list隊列的所有元素
void put_list(INTLISTlist, char *name)
{
    INTLIST::iterator plist;

    cout << "The contents of " << name << " : ";
    for(plist = list.begin(); plist != list.end(); plist++)
        cout << *plist << " ";
    cout<<endl;
}

//測試list容器的功能
void main(void)
{
//list1對象初始爲空
    INTLIST list1;  
    //list2對象最初有10個值爲6的元素
    INTLIST list2(10,6);
    //list3對象最初有3個值爲6的元素
    INTLIST list3(list2.begin(),--list2.end());

    //聲明一個名爲i的雙向迭代器
    INTLIST::iterator i;

    //從前向後顯示各list對象的元素
    put_list(list1,"list1");
    put_list(list2,"list2");
    put_list(list3,"list3");
   
//從list1序列後面添加兩個元素
list1.push_back(2);
list1.push_back(4);
cout<<"list1.push_back(2) andlist1.push_back(4):"<<endl;
    put_list(list1,"list1");

//從list1序列前面添加兩個元素
list1.push_front(5);
list1.push_front(7);
cout<<"list1.push_front(5) andlist1.push_front(7):"<<endl;
    put_list(list1,"list1");

//在list1序列中間插入數據
list1.insert(++list1.begin(),3,9);
cout<<"list1.insert(list1.begin()+1,3,9):"<<endl;
    put_list(list1,"list1");

//測試引用類函數
cout<<"list1.front()="<<list1.front()<<endl;
cout<<"list1.back()="<<list1.back()<<endl;

//從list1序列的先後各移去一個元素
list1.pop_front();
list1.pop_back();
cout<<"list1.pop_front() andlist1.pop_back():"<<endl;
    put_list(list1,"list1");

//清除list1中的第2個元素
list1.erase(++list1.begin());
cout<<"list1.erase(++list1.begin()):"<<endl;
    put_list(list1,"list1");

//對list2賦值並顯示
list2.assign(8,1);
cout<<"list2.assign(8,1):"<<endl;
    put_list(list2,"list2");

//顯示序列的狀態信息
cout<<"list1.max_size(): "<<list1.max_size()<<endl;
cout<<"list1.size(): "<<list1.size()<<endl;
cout<<"list1.empty(): "<<list1.empty()<<endl;

//list序列容器的運算
    put_list(list1,"list1");
    put_list(list3,"list3");
cout<<"list1>list3: "<<(list1>list3)<<endl;
cout<<"list1<list3: "<<(list1<list3)<<endl;

//對list1容器排序
list1.sort();
    put_list(list1,"list1");
   
//結合處理
list1.splice(++list1.begin(),list3);
    put_list(list1,"list1");
    put_list(list3,"list3");
}

 
 
 
 
http://www.cppblog.com/vontroy/archive/2010/05/16/115501.html
 
map映照容器的元素數據是一個鍵值和一個映照數據組成的,鍵值與映照數據之間具備一一映照的關係。
        map映照容器的數據結構是採用紅黑樹來實現的,插入鍵值的元素不容許重複,比較函數只對元素的鍵值進行比較,元素的各項數據可經過鍵值檢索出來。
        使用map容器須要頭文件包含語句「#include<map>」,map文件也包含了對multimap多重映照容器的定義。
        
一、map建立、元素插入和遍歷訪問
        
建立map對象,鍵值與映照數據的類型由本身定義。在沒有指定比較函數時,元素的插入位置是按鍵值由小到大插入到黑白樹中去的,下面這個程序詳細說明了如何操做map容器。
 1#include <map>
 2#include <string>
 3#include <iostream>
 4
 5using std :: cout ;
 6using std :: endl ;
 7using std :: string ;
 8using std :: map ;
 9
10int main()
11 {
12     //定義map對象,當前沒有任何元素
13     map<string,float> m ;
14     
15     //插入元素,按鍵值的由小到大放入黑白樹中
16     m["Jack"] = 98.5 ;
17     m["Bomi"] = 96.0 ;
18     m["Kate"] = 97.5 ;
19     
20     //先前遍歷元素
21     map<string,float> :: iterator it ;
22     for(it = m.begin() ; it != m.end() ; it ++)
23     {
24          cout << (*it).first << " : " << (*it).second << endl ;
25     }
26     
27     return 0 ;
28}
29
        運行結果:
                          Bomi :96
                          Jack  :98.5
                          Kate  :97.5
        程序編譯試,會產生代號爲「warning C4786」 的警告, 「4786」 是標記符超長警告的代號。能夠在程序的頭文件包含代碼的前面使用"#pragma waring(disable:4786)" 宏語句,強制編譯器忽略該警告。4786號警告對程序的正確性和運行並沒有影響。
二、刪除元素
        map
映照容器的 erase() 刪除元素函數,能夠刪除某個迭代器位置上的元素、等於某個鍵值的元素、一個迭代器區間上的全部元素,固然,也可以使用clear()方法清空map映照容器。
        下面這個程序演示了刪除map容器中鍵值爲28的元素:
 1#include <map>
 2#include <string>
 3#include <iostream>
 4
 5using std :: cout ;
 6using std :: endl ;
 7using std :: string ;
 8using std :: map ;
 9
10int main()
11 {
12    //定義map對象,當前沒有任何元素
13    map<int, char> m ;
14    //插入元素,按鍵值的由小到大放入黑白樹中
15    m[25] = 'm' ;
16    m[28] = 'k' ;
17    m[10] = 'x' ;
18    m[30] = 'a' ;
19    //刪除鍵值爲28的元素
20    m.erase(28) ;
21    //向前遍歷元素
22    map<int, char> :: iterator it ;
23    for(it = m.begin() ; it != m.end() ; it ++)
24    {
25        //輸出鍵值與映照數據
26        cout << (*it).first << " : " << (*it).second << endl ;
27    }
28    return 0 ;
29}
30
運行結果:
                     10 : x
                     25 : m
                     30 : a
三、元素反向遍歷
      能夠用反向迭代器reverse_iterator反向遍歷map映照容器中的數據,它須要rbegin()方法和rend()方法指出反向遍歷的起始位置和終止位置。
 1#include <map>
 2#include <string>
 3#include <iostream>
 4
 5using std :: cout ;
 6using std :: endl ;
 7using std :: string ;
 8using std :: map ;
 9
10int main()
11 {
12    //定義map對象,當前沒有任何元素
13    map<int, char> m ;
14    //插入元素,按鍵值的由小到大放入黑白樹中
15    m[25] = 'm' ;
16    m[28] = 'k' ;
17    m[10] = 'x' ;
18    m[30] = 'a' ;
19    //反向遍歷元素
20    map<int, char> :: reverse_iterator rit ;
21    for( rit = m.rbegin() ; rit != m.rend() ; rit ++)
22    {
23        //輸入鍵值與映照數據
24        cout << (*rit).first << " : " << (*rit).second << endl ;
25    }
26    return 0 ;
27}
28
運行結果:
                  30 : a
                  28 : k
                  25 : m
                  10 : x
四、元素的搜索
       
使用find()方法來搜索某個鍵值,若是搜索到了,則返回該鍵值所在的迭代器位置,不然,返回end()迭代器位置。因爲map採用黑白樹數據結構來實現,因此搜索速度是極快的。
       下面這個程序搜索鍵值爲28的元素:
 1#include <map>
 2#include <string>
 3#include <iostream>
 4
 5using std :: cout ;
 6using std :: endl ;
 7using std :: string ;
 8using std :: map ;
 9
10int main()
11 {
12    //定義map對象,當前沒有任何元素
13    map<int, char> m ;
14    //插入元素,按鍵值的由小到大放入黑白樹中
15    m[25] = 'm' ;
16    m[28] = 'k' ;
17    m[10] = 'x' ;
18    m[30] = 'a' ;
19    map<int, char> :: iterator it ;
20    it = m.find(28) ;
21    if(it != m.end())  //搜索到該鍵值
22            cout << (*it).first << " : " << ( *it ).second << endl ;
23    else
24            cout << "not found it" << endl ;
25    return 0 ;
26}
27
五、自定義比較函數
        
將元素插入到map中去的時候,map會根據設定的比較函數將該元素放到該放的節點上去。在定義map的時候,若是沒有指定比較函數,那麼採用默認的比較函數,即按鍵值由小到大的順序插入元素。在不少狀況下,須要本身編寫比較函數。
        編寫方法有兩種。
        (1)若是元素不是結構體,那麼,能夠編寫比較函數。下面這個程序編寫的比較規則是要求按鍵值由大到小的順序將元素插入到map中
 1#include <map>
 2#include <string>
 3#include <iostream>
 4
 5using std :: cout ;
 6using std :: endl ;
 7using std :: string ;
 8using std :: map ;
 9
10//自定義比較函數 myComp
11struct myComp
12 {
13    bool operator() (const int &a, const int &b)
14    {
15        if(a != b) return a > b ;
16        else  return a > b ;
17    }
18} ;
19
20int main()
21{
22    //定義map對象,當前沒有任何元素
23    map<int, char> m ;
24    //插入元素,按鍵值的由小到大放入黑白樹中
25    m[25] = 'm' ;
26    m[28] = 'k' ;
27    m[10] = 'x' ;
28    m[30] = 'a' ;
29    //使用前向迭代器中序遍歷map
30    map<int, char,myComp> :: iterator it ;
31    for(it = m.begin() ; it != m.end() ; it ++)
32            cout << (*it).first << " : " << (*it).second << endl ;
33    return 0 ;
34}
35
運行結果:
                  30 :a
                  28 :k
                  25 :m
                  10 :x
       (2)若是元素是結構體,那麼,能夠直接把比較函數寫在結構體內。下面的程序詳細說明了如何操做:
 1#include <map>
 2#include <string>
 3#include <iostream>
 4
 5using std :: cout ;
 6using std :: endl ;
 7using std :: string ;
 8using std :: map ;
 9
10struct Info
11 {
12    string name ;
13    float score ;
14    //重載 「<」操做符,自定義排列規則
15    bool operator < (const Info &a) const
16    {
17        //按score由大到小排列。若是要由小到大排列,使用「>」號便可
18        return a.score < score ;
19    }
20} ;
21
22int main()
23{
24    //定義map對象,當前沒有任何元素
25    map<Info, int> m ;
26    //定義Info結構體變量
27    Info info ;
28    //插入元素,按鍵值的由小到大放入黑白樹中
29    info.name = "Jack" ;
30    info.score = 60 ;
31    m[info] = 25 ;
32    info.name = "Bomi" ;
33    info.score = 80 ;
34    m[info] = 10 ;
35    info.name = "Peti" ;
36    info.score = 66.5 ;
37    m[info] = 30 ;
38    //使用前向迭代器中序遍歷map
39    map<Info,int> :: iterator it ;
40    for(it = m.begin() ; it != m.end() ; it ++)
41    {
42            cout << (*it).second << " : " ;
43            cout << ((*it).first).name << " : " << ((*it).first).score << endl ;
44    }
45    return 0 ;
46}
47
運行結果:
                  10 :Bomi   80
                  30 :Peti     66.5
                  25 :Jack    60
六、用map實現數字分離
      對數字的各位進行分離,採用取餘等數學方法是很耗時的。而把數字當成字符串,使用map的映照功能,很方便地實現了數字分離。下面這個程序將一個字符串中的字符當成數字,並將各位的數值相加,最後輸出各位的和。
 1#include <string>
 2#include <map>
 3#include <iostream>
 4
 5using std :: cout ;
 6using std :: endl ;
 7using std :: string ;
 8using std :: map ;
 9
10int main()
11 {
12    //定義map對象,當前沒有任何元素
13    map<char, int> m ;
14
15    //賦值:字符映射數字
16    m['0'] = 0 ;
17    m['1'] = 1 ;
18    m['2'] = 2 ;
19    m['3'] = 3 ;
20    m['4'] = 4 ;
21    m['5'] = 5 ;
22    m['6'] = 6 ;
23    m['7'] = 7 ;
24    m['8'] = 8 ;
25    m['9'] = 9 ;
26    /**//*上面的10條賦值語句可採用下面這個循環簡化代碼編寫
27    for(int j = 0 ; j < 10 ; j++)
28    {
29            m['0' + j] = j ;
30    }
31    */
32    string sa, sb ;
33    sa = "6234" ;
34    int i ;
35    int sum = 0 ;
36    for ( i = 0 ; i < sa.length() ; i++ )
37            sum += m[sa[i]] ;
38    cout << "sum = " << sum << endl ;
39    return 0 ;
40}
41
七、數字映照字符的map寫法
      
在不少狀況下,須要實現將數字映射爲相應的字符,看看下面的程序:
 1#include <string>
 2#include <map>
 3#include <iostream>
 4
 5using std :: cout ;
 6using std :: endl ;
 7using std :: string ;
 8using std :: map ;
 9
10int main()
11 {
12    //定義map對象,當前沒有任何元素
13    map<int, char> m ;
14
15    //賦值:字符映射數字
16    m[0] = '0' ;
17    m[1] = '1' ;
18    m[2] = '2' ;
19    m[3] = '3' ;
20    m[4] = '4' ;
21    m[5] = '5' ;
22    m[6] = '6' ;
23    m[7] = '7' ;
24    m[8] = '8' ;
25    m[9] = '9' ;
26    /**//*上面的10條賦值語句可採用下面這個循環簡化代碼編寫
27    for(int j = 0 ; j < 10 ; j++)
28    {
29            m[j] = '0' + j ;
30    }
31    */
32    int n = 7 ;
33    string s = "The number is " ;
34    cout << s + m[n] << endl ;
35    return 0 ;
36}
37
運行結果:
                  The number is 7
 
 
 
 
 
 
 
 
 
 
 
 

準模板庫就是類與函數模板的大集合。STL共有6種組件:容器,容器適配器,迭代器,算法,函數對象和函數適配器。

一、容器:

容器是用來存儲和組織其餘對象的對象。STL容器類的模板在標準頭文件中定義。主要以下所示

①序列容器

基本的序列容器是上面圖中的前三類:

關於三者的優缺點主要是:

A:vector<T>矢量容器:能夠隨機訪問容器的內容,在序列末尾添加或刪除對象,可是由於是從尾部刪除,過程很是慢,由於必須移動插入或刪除點後面的全部對象。

 

矢量容器的操做:(本身之前有個表,貼出來你們看看)

其中的capacity表示容量,size是當前數據個數。矢量容器若是用戶添加一個元素時容量已滿,那麼就增長當前容量的一半的內存,好比如今是500了,用戶添加進第501個,那麼他會再開拓250個,總共就750個了。因此矢量容器當你添加數據量很大的時候,須要注意這一點哦。。。

 

若是想用迭代器訪問元素是比較簡單的,使用迭代器輸出元素的循環相似以下:

 

  1. vector<int>::iterator表示矢量容器vector<int>的迭代器。。。  
  1. for(vector<int>::iterator iter = number.begin(); iter<number.end(); iter++)//這裏的iterator iter算是一個指針了  
  2.      cout << " " << *iter;  
固然也能夠用咱們本身的方法,可是感受用上面的更好一些。

 

 

  1. for(vector<int>::size_type i=0; i<number.size(); i++)  
  2.     cout << " " << number[i]  

 

 

排序矢量元素:

對矢量元素的排序可使用<algorithm>頭文件中定義的sort()函數模板來對一個矢量容器進行排序。可是有幾點要求須要注意

 

  1. sort()函數模板用<運算符來排列元素的順序,因此容器中對象必須能夠進行<運算,若是是基本類型,能夠直接調用sort(),若是是自定義對象,必須對<進行運算符重載
  2. 兩個迭代器的指向必須是序列的第一個對象和最後一個對象的下一個位置。好比:sort(people.begin(), people.end());//這裏兩個參數就是迭代器的意思了

B:deque<T>容器:很是相似vector<T>,且支持相同的操做,可是它還能夠在序列開頭添加和刪除。

 

deque<T>雙端隊列容器與矢量容器基本相似,具備相同的函數成員,可是有點不一樣的是它支持從兩端插入和刪除數據,因此就有了兩個函數:push_front和pop_front。而且有兩個迭代器變量

 

  1. <span style="font-size:18px;">#include <deque>  
  2. deque<int> data;//建立雙端隊列容器對象  
  3. deque<int>::iterator iter;//書序迭代器  
  4. deque<int>::reverse_iterator riter;//逆序迭代器。  
  5. //iter和riter是不一樣的類型</span>  

 


C:list<T>容器是雙向鏈表,所以能夠有效的在任何位置添加和刪除。列表的缺點是不能隨機訪問內容,要想訪問內容必須在列表的內部從頭開始便利內容,或者從尾部開始。

 

 

②關聯容器

map<K, T>映射容器:K表示鍵,T表示對象,根據特定的鍵映射到對象,能夠進行快速的檢索。

有關它的建立以及查找的操做做以下總結

 

  1. //建立映射容器  
  2. map<person, string> phonebook;  
  3.   
  4. //建立要存儲的對象  
  5. pair<person, string> entry = pair<person, string>(person("mel", "Gibson"), "213 345 567");  
  6.   
  7. //插入對象  
  8. phonebook.insert(entry);//只要映射中沒有相同的鍵,就能夠插入entry  
  9.   
  10. //訪問對象  
  11. string number = phonebook[person("mel", "Gibson")];//若是這個鍵不存在,會默認將這個鍵插入  
  12.   
  13. //若是不想在找不到的時候插入,能夠先查找而後再檢索  
  14. person key = person("mel", "Gibson");  
  15. map<person, string>::iterator iter = phonebook.find(key);//建立迭代器,就認爲是指針就行了  
  16.   
  17. if(iter != phonebook.end())  
  18.     string  number = iter->second;  


 

 

 

二、容器適配器:

容器適配器是包裝了現有的STL容器類的模板類,提供了一個不一樣的、一般更有限制性的功能。具體以下所示

 

A:queue<T>隊列容器:經過適配器實現先進先出的存儲機制。咱們只能向隊列的末尾添加或從開頭刪除元素。push_back() pop_front()

代碼:queue<string, list<string> > names;(這就是定義的一個適配器)是基於列表建立隊列的。適配器模板的第二個類型形參指定要使用的底層序列容器,主要的操做以下

B:priority_queue<T>優先級隊列容器:是一個隊列,它的頂部老是具備最大或最高優先級。優先級隊列容器與隊列容器一個不一樣點是優先級隊列容器不能訪問隊列後端的元素。

默認狀況下,優先級隊列適配器類使用的是矢量容器vector<T>,固然能夠選擇指定不一樣的序列容器做爲基礎,並選擇一個備用函數對象來肯定元素的優先級代碼以下

 

  1. priority_queue<int, deque<int>, greate<int>> numbers;  

C:stack<T>堆棧容器:其適配器模板在<stack>頭文件中定義,默認狀況下基於deque<T>容器實現向下推棧,即後進先出機制。只能訪問最近剛剛進去的對象

 

 

  1. <span style="font-size:18px;">//定義容器  
  2. stack<person> people;  
  3. //基於列表來定義堆棧  
  4. stack<string, list<string>> names;</span>  

基本操做以下:

 


 

三、迭代器:

具體它的意思還沒怎麼看明白,書上介紹迭代器的行爲與指針相似,這裏作個標記奮鬥,看看後面的例子再給出具體的解釋

具體分爲三個部分:輸入流迭代器、插入迭代器和輸出流迭代器。

看這一章的內容看的我有點抑鬱了都,摘段課本介紹的內容,仍是能夠幫助理解的

<iterator>頭文件中定義了迭代器的幾個模板:①流迭代器做爲指向輸入或輸出流的指針,他們能夠用來在流和任何使用迭代器或目的地之間傳輸數據。②插入迭代器能夠將數據傳輸給一個基本序列容器。頭文件中定義了兩個流迭代器模板:istream_iterator<T>用於輸入流,ostream_iterator<T>用於輸出流。T表示從流中提取數據或寫到流中的對象的類型。頭文件還定義了三個插入模板:insert<T>, back_insert<T>和front_inset<T>。其中T也是指代序列容器中數據的類型。

輸入流迭代器用下面的程序來講明下,可見具體註釋

 

  1. #include <iostream>    
  2. #include <vector>  
  3. #include <numeric>  
  4. #include <sstream>  
  5.   
  6. using namespace std;    
  7.    
  8. int main()  
  9. {  
  10.     //定義矢量容器  
  11.     vector<int> numbers;  
  12.     cout << "請輸入整數值,以字母結束:";  
  13.   
  14.     //定義輸入流迭代器。注意兩個不一樣  
  15.     //一、numberInput(cin)是指定迭代器指向流cin  
  16.     //二、numbersEnd沒有指定,是默認的,默認構造了一個end_of_stream的迭代器,它等價於調用end()  
  17.     istream_iterator<int> numbersInput(cin), numbersEnd;  
  18.   
  19.     //用戶輸入,直到輸入的不是int類型或者終止時結束。   
  20.     while(numbersInput != numbersEnd)  
  21.         numbers.push_back(*numbersInput++);  
  22.   
  23.     cout << "打印輸出:" << numbers.at(3) << endl;  
  24.   
  25.   
  26.     //如何指定輸入流呢?  
  27.       
  28.     //肯定字符串  
  29.     string data("2.1 3.6 36.5 26 34 25 2.9 63.8");  
  30.   
  31.     //指定data爲輸入流input。須要頭文件<sstream>  
  32.     istringstream input(data);  
  33.   
  34.     //定義迭代器  
  35.     istream_iterator<double> begin(input), end;  
  36.   
  37.     //計算數值和。  
  38.     //acculumate爲頭文件<numeric>下定義的函數。  
  39.     //第一個參數是開始迭代器,第二個是終止迭代器(最後一個值的下一個)。第三個是和的初值,注意必須用0.0,用它肯定數據類型是double  
  40.     cout << "打印數據的總和:" << accumulate(begin, end, 0.0) << endl;  
  41. }  

輸出結果:

耽誤時間太多。之後再寫吧

 

四、算法:

算法是操做迭代器提供的一組對象的STL函數模板,對對象的一個操做,能夠與前面的容器迭代器結合起來看。以下圖介紹

五、函數對象:

函數對象是重載()運算符的類類型的對象。就是實現operator()()函數。

函數對象模板在<functional>頭文件中定義,必要時咱們也能夠定義本身的函數對象。作個標記奮鬥,等有具體實例來進行進一步的解釋。

六、函數適配器:

函數適配器是容許合併函數對象以產生一個更復雜的函數對象的函數模板。

 

 

 

Map是STL的一個關聯容器,它提供一對一(其中第一個能夠稱爲關鍵字,每一個關鍵字只能在map中出現一次,第二個可能稱爲該關鍵字的值)的數據處理能力,因爲這個特性,它完成有可能在咱們處理一對一數據的時候,在編程上提供快速通道。這裏說下map內部數據的組織,map內部自建一顆紅黑樹(一種非嚴格意義上的平衡二叉樹),這顆樹具備對數據自動排序的功能,因此在map內部全部的數據都是有序的,後邊咱們會見識到有序的好處。

下面舉例說明什麼是一對一的數據映射。好比一個班級中,每一個學生的學號跟他的姓名就存在着一一映射的關係,這個模型用map可能輕易描述,很明顯學號用int描述,姓名用字符串描述(本篇文章中不用char *來描述字符串,而是採用STL中string來描述),下面給出map描述代碼:

Map<int, string> mapStudent;

1.       map的構造函數

map共提供了6個構造函數,這塊涉及到內存分配器這些東西,略過不表,在下面咱們將接觸到一些map的構造方法,這裏要說下的就是,咱們一般用以下方法構造一個map:

Map<int, string> mapStudent;

2.       數據的插入

在構造map容器後,咱們就能夠往裏面插入數據了。這裏講三種插入數據的方法:

第一種:用insert函數插入pair數據,下面舉例說明(如下代碼雖然是隨手寫的,應該能夠在VC和GCC下編譯經過,你們能夠運行下看什麼效果,在VC下請加入這條語句,屏蔽4786警告 #pragma warning (disable:4786) )

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent.insert(pair<int, string>(1, 「student_one」));

       mapStudent.insert(pair<int, string>(2, 「student_two」));

       mapStudent.insert(pair<int, string>(3, 「student_three」));

       map<int, string>::iterator  iter;

       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)

{

       Cout<<iter->first<<」   」<<iter->second<<end;

}

}

第二種:用insert函數插入value_type數據,下面舉例說明

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent.insert(map<int, string>::value_type (1, 「student_one」));

       mapStudent.insert(map<int, string>::value_type (2, 「student_two」));

       mapStudent.insert(map<int, string>::value_type (3, 「student_three」));

       map<int, string>::iterator  iter;

       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)

{

       Cout<<iter->first<<」   」<<iter->second<<end;

}

}

第三種:用數組方式插入數據,下面舉例說明

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent[1] =  「student_one」;

       mapStudent[2] =  「student_two」;

       mapStudent[3] =  「student_three」;

       map<int, string>::iterator  iter;

       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)

{

       Cout<<iter->first<<」   」<<iter->second<<end;

}

}

以上三種用法,雖然均可以實現數據的插入,可是它們是有區別的,固然了第一種和第二種在效果上是完成同樣的,用insert函數插入數據,在數據的插入上涉及到集合的惟一性這個概念,即當map中有這個關鍵字時,insert操做是插入數據不了的,可是用數組方式就不一樣了,它能夠覆蓋之前該關鍵字對應的值,用程序說明

mapStudent.insert(map<int, string>::value_type (1, 「student_one」));

mapStudent.insert(map<int, string>::value_type (1, 「student_two」));

上面這兩條語句執行後,map中1這個關鍵字對應的值是「student_one」,第二條語句並無生效,那麼這就涉及到咱們怎麼知道insert語句是否插入成功的問題了,能夠用pair來得到是否插入成功,程序以下

Pair<map<int, string>::iterator, bool> Insert_Pair;

Insert_Pair = mapStudent.insert(map<int, string>::value_type (1, 「student_one」));

咱們經過pair的第二個變量來知道是否插入成功,它的第一個變量返回的是一個map的迭代器,若是插入成功的話Insert_Pair.second應該是true的,不然爲false。

下面給出完成代碼,演示插入成功與否問題

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

Pair<map<int, string>::iterator, bool> Insert_Pair;

       Insert_Pair = mapStudent.insert(pair<int, string>(1, 「student_one」));

       If(Insert_Pair.second == true)

       {

              Cout<<」Insert Successfully」<<endl;

       }

       Else

       {

              Cout<<」Insert Failure」<<endl;

       }

       Insert_Pair = mapStudent.insert(pair<int, string>(1, 「student_two」));

       If(Insert_Pair.second == true)

       {

              Cout<<」Insert Successfully」<<endl;

       }

       Else

       {

              Cout<<」Insert Failure」<<endl;

       }

       map<int, string>::iterator  iter;

       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)

{

       Cout<<iter->first<<」   」<<iter->second<<end;

}

}

你們能夠用以下程序,看下用數組插入在數據覆蓋上的效果

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent[1] =  「student_one」;

       mapStudent[1] =  「student_two」;

       mapStudent[2] =  「student_three」;

       map<int, string>::iterator  iter;

       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)

{

       Cout<<iter->first<<」   」<<iter->second<<end;

}

}

3.       map的大小

在往map裏面插入了數據,咱們怎麼知道當前已經插入了多少數據呢,能夠用size函數,用法以下:

Int nSize = mapStudent.size();

4.       數據的遍歷

這裏也提供三種方法,對map進行遍歷

第一種:應用前向迭代器,上面舉例程序中處處都是了,略過不表

第二種:應用反相迭代器,下面舉例說明,要體會效果,請自個動手運行程序

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent.insert(pair<int, string>(1, 「student_one」));

       mapStudent.insert(pair<int, string>(2, 「student_two」));

       mapStudent.insert(pair<int, string>(3, 「student_three」));

       map<int, string>::reverse_iterator  iter;

       for(iter = mapStudent.rbegin(); iter != mapStudent.rend(); iter++)

{

       Cout<<iter->first<<」   」<<iter->second<<end;

}

}

第三種:用數組方式,程序說明以下

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent.insert(pair<int, string>(1, 「student_one」));

       mapStudent.insert(pair<int, string>(2, 「student_two」));

       mapStudent.insert(pair<int, string>(3, 「student_three」));

       int nSize = mapStudent.size()

//此處有誤,應該是 for(int nIndex = 1; nIndex <= nSize; nIndex++) 

//by rainfish

       for(int nIndex = 0; nIndex < nSize; nIndex++)

{

       Cout<<mapStudent[nIndex]<<end;

}

}

5.       數據的查找(包括斷定這個關鍵字是否在map中出現)

在這裏咱們將體會,map在數據插入時保證有序的好處。

要斷定一個數據(關鍵字)是否在map中出現的方法比較多,這裏標題雖然是數據的查找,在這裏將穿插着大量的map基本用法。

這裏給出三種數據查找方法

第一種:用count函數來斷定關鍵字是否出現,其缺點是沒法定位數據出現位置,因爲map的特性,一對一的映射關係,就決定了count函數的返回值只有兩個,要麼是0,要麼是1,出現的狀況,固然是返回1了

第二種:用find函數來定位數據出現位置,它返回的一個迭代器,當數據出現時,它返回數據所在位置的迭代器,若是map中沒有要查找的數據,它返回的迭代器等於end函數返回的迭代器,程序說明

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent.insert(pair<int, string>(1, 「student_one」));

       mapStudent.insert(pair<int, string>(2, 「student_two」));

       mapStudent.insert(pair<int, string>(3, 「student_three」));

       map<int, string>::iterator iter;

       iter = mapStudent.find(1);

if(iter != mapStudent.end())

{

       Cout<<」Find, the value is 」<<iter->second<<endl;

}

Else

{

       Cout<<」Do not Find」<<endl;

}

}

第三種:這個方法用來斷定數據是否出現,是顯得笨了點,可是,我打算在這裏講解

Lower_bound函數用法,這個函數用來返回要查找關鍵字的下界(是一個迭代器)

Upper_bound函數用法,這個函數用來返回要查找關鍵字的上界(是一個迭代器)

例如:map中已經插入了1,2,3,4的話,若是lower_bound(2)的話,返回的2,而upper-bound(2)的話,返回的就是3

Equal_range函數返回一個pair,pair裏面第一個變量是Lower_bound返回的迭代器,pair裏面第二個迭代器是Upper_bound返回的迭代器,若是這兩個迭代器相等的話,則說明map中不出現這個關鍵字,程序說明

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent[1] =  「student_one」;

       mapStudent[3] =  「student_three」;

       mapStudent[5] =  「student_five」;

       map<int, string>::iterator  iter;

iter = mapStudent.lower_bound(2);

{

       //返回的是下界3的迭代器

       Cout<<iter->second<<endl;

}

iter = mapStudent.lower_bound(3);

{

       //返回的是下界3的迭代器

       Cout<<iter->second<<endl;

}

 

iter = mapStudent.upper_bound(2);

{

       //返回的是上界3的迭代器

       Cout<<iter->second<<endl;

}

iter = mapStudent.upper_bound(3);

{

       //返回的是上界5的迭代器

       Cout<<iter->second<<endl;

}

 

Pair<map<int, string>::iterator, map<int, string>::iterator> mapPair;

mapPair = mapStudent.equal_range(2);

if(mapPair.first == mapPair.second)
       {

       cout<<」Do not Find」<<endl;

}

Else

{

Cout<<」Find」<<endl;
}

mapPair = mapStudent.equal_range(3);

if(mapPair.first == mapPair.second)
       {

       cout<<」Do not Find」<<endl;

}

Else

{

Cout<<」Find」<<endl;
}

}

6.       數據的清空與判空

清空map中的數據能夠用clear()函數,斷定map中是否有數據能夠用empty()函數,它返回true則說明是空map

7.       數據的刪除

這裏要用到erase函數,它有三個重載了的函數,下面在例子中詳細說明它們的用法

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent.insert(pair<int, string>(1, 「student_one」));

       mapStudent.insert(pair<int, string>(2, 「student_two」));

       mapStudent.insert(pair<int, string>(3, 「student_three」));

 

//若是你要演示輸出效果,請選擇如下的一種,你看到的效果會比較好

       //若是要刪除1,用迭代器刪除

       map<int, string>::iterator iter;

       iter = mapStudent.find(1);

       mapStudent.erase(iter);

 

       //若是要刪除1,用關鍵字刪除

       Int n = mapStudent.erase(1);//若是刪除了會返回1,不然返回0

 

       //用迭代器,成片的刪除

       //一下代碼把整個map清空

       mapStudent.earse(mapStudent.begin(), mapStudent.end());

       //成片刪除要注意的是,也是STL的特性,刪除區間是一個前閉後開的集合

 

       //自個加上遍歷代碼,打印輸出吧

}

8.       其餘一些函數用法

這裏有swap,key_comp,value_comp,get_allocator等函數,感受到這些函數在編程用的不是不少,略過不表,有興趣的話能夠自個研究

9.       排序

這裏要講的是一點比較高深的用法了,排序問題,STL中默認是採用小於號來排序的,以上代碼在排序上是不存在任何問題的,由於上面的關鍵字是int型,它自己支持小於號運算,在一些特殊狀況,好比關鍵字是一個結構體,涉及到排序就會出現問題,由於它沒有小於號操做,insert等函數在編譯的時候過不去,下面給出兩個方法解決這個問題

第一種:小於號重載,程序舉例

#include <map>

#include <string>

Using namespace std;

Typedef struct tagStudentInfo

{

       Int      nID;

       String   strName;

}StudentInfo, *PStudentInfo;  //學生信息

 

Int main()

{

    int nSize;

       //用學生信息映射分數

       map<StudentInfo, int>mapStudent;

    map<StudentInfo, int>::iterator iter;

       StudentInfo studentInfo;

       studentInfo.nID = 1;

       studentInfo.strName = 「student_one」;

       mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90));

       studentInfo.nID = 2;

       studentInfo.strName = 「student_two」;

mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80));


for (iter=mapStudent.begin(); iter!=mapStudent.end(); iter++)

    cout<<iter->first.nID<<endl<<iter->first.strName<<endl<<iter->second<<endl;

 

}

以上程序是沒法編譯經過的,只要重載小於號,就OK了,以下:

Typedef struct tagStudentInfo

{

       Int      nID;

       String   strName;

       Bool operator < (tagStudentInfo const& _A) const

       {

              //這個函數指定排序策略,按nID排序,若是nID相等的話,按strName排序

              If(nID < _A.nID)  return true;

              If(nID == _A.nID) return strName.compare(_A.strName) < 0;

              Return false;

       }

}StudentInfo, *PStudentInfo;  //學生信息

第二種:仿函數的應用,這個時候結構體中沒有直接的小於號重載,程序說明

#include <map>

#include <string>

Using namespace std;

Typedef struct tagStudentInfo

{

       Int      nID;

       String   strName;

}StudentInfo, *PStudentInfo;  //學生信息

 

Classs sort

{

       Public:

       Bool operator() (StudentInfo const &_A, StudentInfo const &_B) const

       {

              If(_A.nID < _B.nID) return true;

              If(_A.nID == _B.nID) return _A.strName.compare(_B.strName) < 0;

              Return false;

       }

};

 

Int main()

{

       //用學生信息映射分數

       Map<StudentInfo, int, sort>mapStudent;

       StudentInfo studentInfo;

       studentInfo.nID = 1;

       studentInfo.strName = 「student_one」;

       mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90));

       studentInfo.nID = 2;

       studentInfo.strName = 「student_two」;

mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80));

}

10.   另外

因爲STL是一個統一的總體,map的不少用法都和STL中其它的東西結合在一塊兒,好比在排序上,這裏默認用的是小於號,即less<>,若是要從大到小排序呢,這裏涉及到的東西不少,在此沒法一一加以說明。

還要說明的是,map中因爲它內部有序,由紅黑樹保證,所以不少函數執行的時間複雜度都是log2N的,若是用map函數能夠實現的功能,而STL  Algorithm也能夠完成該功能,建議用map自帶函數,效率高一些。

相關文章
相關標籤/搜索