5. STL編程五

1. STL的六大組件:ios

  容器(Container)算法

  算法(Algorithm)數組

  迭帶器(Iterator)oracle

  仿函數(Function object)app

  適配器(Adaptor)less

  空間配置器(allocator)函數

#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;

int main()
{
    //容器:
    vector<int> myint{ 1,2,3,4,5 };    
    myint.push_back(10);

    //算法:
    for_each(myint.begin(), myint.end(), [](int x) {cout << x <<" "; });
    cout << endl;
    
    //迭帶器:
    auto it = myint.begin() + 2;
    for (auto ib = myint.begin(), ie = myint.end(); ib != ie; ib++)
    {
        cout << *ib << " ";
    }
    cout << endl;

    list<int> mylist{ 1,2,3,4,5 };
    mylist.push_front(10);
    //auto ib1 = mylist.begin() + 2;    //鏈表每次只能前進一個
    auto ib1 = mylist.begin()++;        //迭帶器自動適應容器

    for_each(mylist.begin(), mylist.end(), [](int x) {cout << x << " "; });
    cout << endl;

    system("pause");
    return 0;
}

    

2. 容器類別:性能

  序列式容器:排列次序取決於插入時機和位置google

  關聯式容器:排列次序取決於特定準則spa

    

  2.1 線性容器 ( array ):

#include <iostream>
#include <array>
#include <algorithm>
using namespace std;

//array容器在棧區,自動回收內存,不能增刪查改,
int main()
{
    array<int, 10> MyArr{ 1,2,3,4,5,6,7,8,9,0 };
    for (auto ib = MyArr.begin(), ie = MyArr.end(); ib != ie; ib++)
    {
        //cout << typeid(ib).name() << ": ";
        cout << *ib << " ";
    }
    cout << endl;

    for (auto i:MyArr)
    {
        cout << i << " ";
    }
    cout << endl;

    for_each(MyArr.begin(), MyArr.end(), [](int & x) {x += 1; });
    for_each(MyArr.begin(), MyArr.end(), [](int x) {cout << x << " "; });
    cout << endl;

    system("pause");
    return 0;
}

    

  2.2 線性容器 ( vector ):

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

//vector在堆區,能夠增刪查改,
int main()
{
    vector<int> MyVec{ 1,2,3,4,5,6,7,8,9,0 };
    for (auto ib = MyVec.begin() + 3, ie = MyVec.end(); ib != ie; ib++)    //vector迭帶器能夠+3
    {
        cout << *ib << " ";
    }
    cout << endl;

    for (auto i : MyVec)
    {
        cout << i << " ";
    }
    cout << endl;

    for_each(MyVec.begin(), MyVec.end(), [](int & x) {x += 1; });
    for_each(MyVec.begin(), MyVec.end(), [](int x) {cout << x << " "; });
    cout << endl;

    system("pause");
    return 0;
}

    

  2.3 線性容器 ( forwardlist ):單鏈表( forward:前進 )==>只能前進,不能後退

#include <iostream>
#include <forward_list>    //單鏈表(forward:前進)==>只能前進,不能後退
#include <algorithm>
using namespace std;

int main()
{
    forward_list<int> my{ 1,2,3,4,5,6,7,8,9,0 };
    for (auto ib = my.begin(), ie = my.end(); ib != ie; ib++)    //ib++能夠;可是ib--不行
    {
        cout << *ib << " ";
    }
    cout << endl;

    for (auto i : my)
    {
        cout << i << " ";
    }
    cout << endl;

    for_each(my.begin(), my.end(), [](int & x) {x += 1; });
    for_each(my.begin(), my.end(), [](int x) {cout << x << " "; });
    cout << endl;

    system("pause");
    return 0;
}

    

  2.4 線性容器 ( list ):雙鏈表==>既能夠前進,也能夠後退

#include <iostream>
#include <list>            //雙鏈表
#include <algorithm>
using namespace std;

int main()
{
    list<int> my{ 1,2,3,4,5,6,7,8,9,0 };
    for (auto ib = my.begin(), ie = my.end(); ib != ie; ib++)    //ib++,ib--能夠;可是ib+3不行
    {
        cout << *ib << " ";
    }
    cout << endl;

    for (auto i : my)
    {
        cout << i << " ";
    }
    cout << endl;

    for_each(my.begin(), my.end(), [](int & x) {x += 1; });
    for_each(my.begin(), my.end(), [](int x) {cout << x << " "; });
    cout << endl;

    system("pause");
    return 0;
}

    

  2.5 線性容器 (deque): 雙端隊列(分塊) ==>性能綜合的要求(增、刪、查、改)

#include <iostream>
#include <deque>    //雙端隊列(分塊數據模型),在堆上
#include <algorithm>
using namespace std;

int main()
{
    deque<int> my{ 1,2,3,4,5,6,7,9 };
    cout << "最大容量:" << my.max_size() << endl;    //最大容量由內存決定
    cout << "當前容量:" << my.size() << endl;
    cout << "第一個元素:" << my.front() << endl;
    cout << "最後一個元素:" << my.back() << endl;

    for (auto ib = my.begin(), ie = my.end(); ib != ie; ib++)    
    {
        cout << *ib << " ";
    }
    cout << endl;

    for (auto i : my)
    {
        cout << i << " ";
    }
    cout << endl;

    for_each(my.begin(), my.end(), [](int & x) {x += 1; });
    for_each(my.begin(), my.end(), [](int x) {cout << x << " "; });
    cout << endl;

    system("pause");
    return 0;
}

    

    deque的應用:

#include <iostream>
#include <deque>    //雙端隊列(分塊數據模型),在堆上
#include <algorithm>
using namespace std;

int main()
{
    deque<int> my{ 1,2,3,4,5,6,7,9 };
    for_each(my.begin(), my.end(), [](int x) {cout << x << " "; });
    cout << endl;

    my.push_back(10);                  //尾部插入數據10
    for_each(my.begin(), my.end(), [](int x) {cout << x << " "; });
    cout << endl;

    my.push_front(101);                //頭部插入
    for_each(my.begin(), my.end(), [](int x) {cout << x << " "; });
    cout << endl;

    my.insert(my.begin() + 5, 99);    //任意位置插入
    for_each(my.begin(), my.end(), [](int x) {cout << x << " "; });
    cout << endl;

    my.pop_front();              //頭部刪除
    my.pop_back();               //尾部刪除
    for_each(my.begin(), my.end(), [](int x) {cout << x << " "; });
    cout << endl;

    my.erase(my.begin() + 4);    //任意位置刪除
    for_each(my.begin(), my.end(), [](int x) {cout << x << " "; });
    cout << endl;

    for (int i = 0; i < my.size(); i++)
    {
        cout << my[i] << " ";        //能夠用[]訪問其中的元素,類模板中重載了[]
    }
    cout << endl;

    for (auto cb = my.cbegin(), ce = my.cend(); cb != ce; cb++)    //cbegin(),cend()是常量迭代器;c表示const(只讀)
    {
        cout << *cb << " ";
        //*cb = 1;    //常量迭代器,只能讀,不能寫
    }
    cout << endl;

    my.clear();        //清空
    for_each(my.begin(), my.end(), [](int x) {cout << x << " "; });
    cout << endl;

    system("pause");
    return 0;
}

    

  2.6 線性容器 ( stack ): 棧

#include <iostream>
#include <stack>    //
#include <list>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    stack<int> myStack;                    //數組棧;stack默認底層是有deque實現的(由於deque的刪除、插入性能也比較高)
    stack<int, list<int>> myListStack;     //鏈式棧
    stack<int, vector<int>> myVecStack;    //能夠任意指定底層的容器

    myStack.push(1);
    myStack.push(2);
    myStack.push(3);
    myStack.push(4);
    myStack.push(5);

    while (!myStack.empty())
    {
        cout << myStack.top() << endl;    //打印棧頂元素
        myStack.pop();

    }

    system("pause");
    return 0;
}

    

  2.7 線性容器 ( queue): 隊列

#include <iostream>
#include <queue>    //隊列
#include <list>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    queue<int> myQ;                    //queue默認底層是deque實現的
    queue<int, list<int>> myListQ;    //指定底層容器爲list
    queue<int, vector<int>> myVecQ;

    myQ.push(1);
    myQ.push(2);
    myQ.push(3);
    myQ.push(4);
    /*
    for (auto i : myQ)        //隊列不容許迭代器訪問
    {
        cout << i << " ";
    }
    cout << endl;
    */

    while (!myQ.empty())
    {
        cout << myQ.front() << endl;    //打印棧頂元素
        myQ.pop();
    }

    system("pause");
    return 0;
}

    

  2.8 線性容器 ( string ): 字符串

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

int main()
{
    string str1 = "1234";
    string str2 = "5678";
    string str3 = str1 + str2;

    str3.push_back('X');
    cout << str3 << endl;

    const char *p = str3.c_str();    //只能用只讀指針const char *,返回內部指針
    cout << p << endl;
    cout << *p << endl;

    for (auto i:str3)
    {
        cout << i << " ";
    }
    cout << endl;

    for (auto cb = str3.cbegin(), ce = str3.cend(); cb != ce; cb++)
    {
        cout << *cb << " ";
    }
    cout << endl;

    system("pause");
    return 0;
}

    

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

int main()
{
    string s1("12345hello hello hahaha");
    s1.insert(s1.begin() + 3, 'X');    //任意位置插入字符
    cout << s1 << endl;

    s1.erase(s1.begin() + 2, s1.begin() + 4);    //刪除從s1.begin() + 2到s1.begin() + 4的字符
    cout << s1 << endl;

    s1.erase(1, 2);                               //刪除從1開始的2個字符
    cout << s1 << endl;

    s1.replace(0, 2, "world");                    //從0位置開始,替換2個位置,替換內容爲world
    cout << s1 << endl;

    s1.replace(s1.begin(), s1.begin()+5, "China");
    cout << s1 << endl;

    s1.replace(5, 0, " haha ");                   //使用replace插入字符串
    cout << s1 << endl;

    cout << s1.find("ha") << endl;                //查找
    cout << s1.find("ha",15) << endl;             //指定位置開始查找

    cout << s1.rfind("ha") << endl;               //反向查找

    cout << s1.find_first_of("1234a") << endl;        //查找第一個屬於"1234a"的字符
    cout << s1.find_first_not_of("1234a") << endl;    //第一個不屬於的字符

    cout << s1.length() << endl;    //字符串的長度
    cout << s1.size() << endl;      //總共分配的長度

    s1.empty();        //清空
    cout << s1 << endl;
    cout << s1.length() << endl;

    system("pause");
    return 0;
}

    

3. 非線性容器:

  3.1 優先隊列( priority_queue ):

#include <iostream>
#include <queue>
#include <list>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    priority_queue<int> myQ;    //優先隊列

    myQ.push(11);
    myQ.push(22);
    myQ.push(33);
    myQ.push(44);
    while (!myQ.empty())
    {
        cout << myQ.top() << endl;    //打印棧頂元素
        myQ.pop();
    }

    system("pause");
    return 0;
}

    

#include <iostream>
#include <queue>
#include <list>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;

struct getMoney
{
    char *com;    //公司
    int money;    //工資
};

struct lessX
{
    bool operator ()(struct getMoney &m1, struct getMoney &m2)    //僞函數
    {
        //return m1.money < m2.money;            //按money排序
        if (strcmp(m1.com, m2.com) >= 0)        //按com排序
            return true;
        else
            return false;
    }
};

int main()
{
    priority_queue<getMoney,deque<getMoney>, lessX> myQ;    //優先隊列
    getMoney getm[4] = { {"google",30},{"baidu",20},{"360",15},{"tencent",10} };

    for (auto i:getm)
    {
        myQ.push(i);
    }
    while (!myQ.empty())
    {
        cout << myQ.top().com << " " << myQ.top().money << endl;    
        myQ.pop();
    }

    system("pause");
    return 0;
}

    

  3.2 位處理容器( bitset ):

#include <iostream>
#include <bitset>    //處理位運算
#include <string>
using namespace std;

int main()
{
    bitset<8> mybit(205);    //1100 1101        8位

    for (int i = 7; i >= 0; i--)    //C++中 高字節在低位 ==>須要逆序打印
    {
        cout << mybit[i];
        if (i % 4 == 0)        //每4位隔開,便於觀察
        {
            cout << " ";
        }
    }
    cout << endl;

    system("pause");
    return 0;
}

    

#include <iostream>
#include <bitset>    //處理位運算
#include <string>
using namespace std;

int main()
{
    char ch = -1;
    bitset<8> mybit(ch);    //8位        
                            //1000 0001    原碼
                            //1111 1110    反碼
                            //1111 1111 補碼

    for (int i = 7; i >= 0; i--)    //C++中 高字節在低位 ==>須要逆序打印
    {
        cout << mybit[i];
        if (i % 4 == 0)        //每4位隔開,便於觀察
        {
            cout << " ";
        }
    }
    cout << endl;

    system("pause");
    return 0;
}

    

#include <iostream>
#include <bitset>    //處理位運算
#include <string>
using namespace std;

int main()
{
    float fl = 19.875;
    cout << (void *)&fl << endl;

    //浮點數沒法處理,只能處理整數,浮點數會轉化爲整數
    bitset<32> mybit(fl);    //32位        float佔4字節
                            
    for (int i = 31; i >= 0; i--)    //C++中 高字節在低位 ==>須要逆序打印
    {
        cout << mybit[i];
        if (i % 4 == 0)        //每4位隔開,便於觀察
        {
            cout << " ";
        }
    }
    cout << endl;

    system("pause");
    return 0;
}

    

   3.3 集合( set ):==>不容許重複的數據

#include <iostream>
#include <set>        //底層是紅黑樹,自動保證平衡,自動生成平衡查找二叉樹
#include <cstdlib>
using namespace std;

int main()
{
    set<int> myset{ 1,2,10,4,6 };    //set是用紅黑樹(會自動調整爲平衡二叉查找樹)實現的
    myset.insert(16);
    myset.insert(15);
    myset.insert(15);                //重複數據會被忽略

    myset.erase(10);    //直接刪除

    for (auto i:myset)
    {
        cout << i << " ";
    }
    cout << endl;

    for (auto ib = myset.begin(), ie = myset.end(); ib != ie; ib++)
    {
        cout << *ib << " ";
    }
    cout << endl;

    for (auto rb = myset.rbegin(), re = myset.rend(); rb != re; rb++)    //反向迭代器
    {
        cout << *rb << " ";
    }
    cout << endl;

    auto it = myset.find(15);        //查找
    if (it != myset.end())
    {
        cout << "find " << *it << endl;
    }
    else
    {
        cout << "not find" << endl;
    }

    cout << myset.size() << endl;    //元素個數
    myset.empty() ;                  //清空
    
    auto it1 = myset.find(15);       //查找
    if (it1 != myset.end())
    {
        myset.erase(it1);            //根據迭代器獲取位置,刪除
    }
    for (auto i : myset)
    {
        cout << i << " ";
    }
    cout << endl;

    system("pause");
    return 0;
}

    

  實現複雜數據類型自動排序:

#include <iostream>
#include <set>        //底層是紅黑樹,自動保證平衡,自動生成平衡查找二叉樹
#include <cstdlib>
#include <cstring>
using namespace std;

struct strless
{
    bool operator()(const char *str1, const char *str2)    //僞函數
    {
        return (strcmp(str1, str2) < 0);
    }
};

int main()
{
    const char *p[] = { "calc","notepad","run","go","123" };
    set<const char *, strless> myset(p, p + 5, strless());        //實現字符串的自動排序
    myset.insert("245");
    for (auto i:myset)
    {
        cout << i << " ";
    }
    cout << endl;

    system("pause");
    return 0;
}

    

  3.4 多集合( multiset ):==>容許有重複數據

#include <iostream>
#include <set>        
#include <cstdlib>
#include <cstring>
using namespace std;

struct strless
{
    bool operator()(const char *str1, const char *str2)    //僞函數
    {
        return (strcmp(str1, str2) < 0);
    }
};

int main()
{
    multiset<int> myset{ 1,2,3,3,3,4,4,5 };    //底層是紅黑樹,每一個元素是一個鏈表
    myset.insert(101);
    myset.insert(101);
    myset.insert(101);

    for (auto i:myset)
    {
        cout << i << " ";
    }
    cout << endl;

    auto it = myset.equal_range(3);        //返回值是pair類型  pair<鏈表起點,鏈表終點>
    //cout << typeid(it).name() << endl;
    for (auto i = it.first; i != it.second; i++)
    {
        cout << *i << " ";
    }
    cout << endl;

    auto it1 = myset.find(101);            //只查找鏈表的第一個元素
    cout << "find: "<<*it1 << endl;

    /*實現複雜數據類型*/
    const char *p[] = { "calc","notepad","run","go","go","go","123" };
    multiset<const char *, strless> myset1(p, p + 7, strless());        //實現字符串的自動排序
    myset1.insert("245");
    for (auto i : myset1)
    {
        cout << i << " ";
    }
    cout << endl;

    system("pause");
    return 0;
}

    

  3.5 哈希表( hash_set ):已被unordered_set 替代

#define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS    //如今用新的容器unordered_set取代了hash_set,須要定義這個宏
#include <iostream>
#include <hash_set>    //底層是哈希表,是無序的
#include <cstring>
using namespace std;

struct strless
{
    bool operator()(const char *str1, const char *str2)    const    //僞函數
    {
        return (strcmp(str1, str2) == 0);    //哈希表只能處理相等
    }
};

int main()
{
    //哈希表,不須要考慮碰撞,查詢的效率最高
    hash_set<int> myset{ 1,19,2,18,3,17,4,16 };
    myset.insert(29);
    for (auto i:myset)
    {
        cout << i << " ";
    }
    cout << endl;

    for (auto ib = myset.begin(), ie = myset.end(); ib != ie; ib++)
    {
        cout << *ib << " ";
    }
    cout << endl;

    for (auto rb = myset.rbegin(), re = myset.rend(); rb != re; rb++)    //反向迭代器
    {
        cout << *rb << " ";
    }
    cout << endl;

    cout << myset.size() << endl;            //元素個數
    cout << myset.bucket_count() << endl;    //64是哈希表的大小

    /*實現複雜數據類型*/
    hash_set<const char *, hash_compare<const char *, strless>> hs;    //hash_compare<const char *, strless>設定哈希函數,根據實際需求(string)設定哈希函數
    hs.insert("apple");
    hs.insert("google");
    hs.insert("Microsoft");
    hs.insert("oracle");

    auto i = hs.find("google");
    if (i != hs.end())
    {
        cout << "find: " << *i << endl;        //爲何輸出apple呢???
    }

    system("pause");
    return 0;
}

    

  3.6 哈希表( unordered_set ):==>不容許重複數據

#include <iostream>
#include <unordered_set>    //凡是帶unordered的容器底層都是哈希表實現,而不是紅黑樹
#include <string>
using namespace std;

int main()
{
    unordered_set<string> myset{ "hello","world","move","jump","abc","last","one","sun","best" };    //unordered_set是無序的,按照哈希函數進行存放
    
    myset.erase(myset.begin());                  //刪除哈希表的第一個
    myset.erase("hello");                        //精準刪除
    //myset.erase(myset.begin(), myset.end());   //刪除某一段

    for (auto i:myset)
    {
        cout << i << " ";
    }
    cout << endl;

    myset.insert("love");    //插入

    for (auto ib = myset.begin(), ie = myset.end(); ib != ie; ib++)
    {
        cout << *ib << " ";
    }
    cout << endl;

    cout << "bucket_count:" << myset.bucket_count() << endl;    //哈希表長度,自動增加,沒有規律
    cout << "max_size:" << myset.max_size() << endl;            //最大大小
    cout << "size:" << myset.size() << endl;                    //當前大小

    for (int i = 0; i < myset.bucket_count(); i++)                   //打印整個哈希表(按bucket打印),可見unordered_set不容許重複,
    {                                                                //而unordered_multiset容許重複
        cout << "bucket:" << i << ":  ";
        for (auto it = myset.begin(i); it != myset.end(i); it++)
        {
            cout << " " << *it;
        }
        cout << endl;
    }

    system("pause");
    return 0;
}

    

    

  3.7 哈希表( unordered_multiset ):==>容許重複數據

#include <iostream>
#include <unordered_set>
#include <string>
using namespace std;

int main()
{
    unordered_multiset<string> myset{ "pig","pig","pig","hen" };
    myset.insert("love");    //插入

    for (auto i:myset)
    {
        cout << i << endl;
    }
    cout << "\n";

    auto it = myset.equal_range("pig");
    while (it.first != it.second)        //相同元素在鏈表上,起點爲first,終點爲second
    {
        cout << *it.first++ << endl;
    }

    system("pause");
    return 0;
}

    

  3.8 映射( map ) ==> 不容許重複 <==> 紅黑樹實現

#include <iostream>
#include <map>        //底層是紅黑樹
#include <cstring>
using namespace std;

//仿函數:STL六大組件之一
struct strless
{
    bool operator()(const char *str1, const char *str2) 
    {
        return (strcmp(str1, str2) < 0);    //字符串對比
    }
};

int main()
{
    map<char *, int> mymap;
    mymap.insert(pair<char *, int>("司令1", 10));
    mymap.insert(pair<char *, int>("司令2", 11));
    mymap.insert(pair<char *, int>("司令3", 13));
    mymap.insert(pair<char *, int>("司令4", 12));
    mymap.insert(pair<char *, int>("司令4", 1211));    //第一個字段,不容許有重複

    for (auto i : mymap)
    {
        cout << i.first << " " << i.second << endl;
    }

    for (auto cb = mymap.cbegin(), ce = mymap.cend(); cb != ce; cb++)
    {
        cout << (*cb).first << " " << (*cb).second << endl;
    }

    auto it = mymap.find("司令2");
    cout << "司令2: " << (*it).second << endl;

    /*map的排序實現*/
    map<char *, int, strless> myMap;    //根據strless仿函數來排序
    myMap.insert(pair<char *, int>("a司令1", 10));
    myMap.insert(pair<char *, int>("c司令2", 11));
    myMap.insert(pair<char *, int>("d司令3", 13));
    myMap.insert(pair<char *, int>("b司令4", 12));

    myMap.erase("b司令4");    //刪除

    for (auto i : myMap)
    {
        cout << i.first << " " << i.second << endl;
    }

    auto ite = myMap.find("c司令2");
    myMap.erase(ite,myMap.end());        //刪除一段(從ite開始到end())
    for (auto i : myMap)
    {
        cout << i.first << " " << i.second << endl;
    }

    auto it2 = myMap.begin()++;        //紅黑樹,鏈式存儲
    //auto it2 = myMap.begin() + 3;    //只能++,不能+3

    cout << myMap["a司令1"] << endl;    //能夠經過下標[]來訪問

    //myMap.clear();    //清空

    system("pause");
    return 0;
}

    

  3.9 多映射( multimap ):==> 容許重複 <==> 紅黑樹實現

#include <iostream>
#include <map>
#include <cstring>
using namespace std;

struct strless
{
    bool operator()(const char *str1, const char *str2)
    {
        return (strcmp(str1, str2) < 0);    //字符串對比
    }
};

int main()
{
    multimap<char *, int, strless> mymap;    //multimap容許重複    加上strless仿函數後能夠進行排序
    mymap.insert(pair<char *, int>("司令1", 10));
    mymap.insert(pair<char *, int>("司令4", 121));
    mymap.insert(pair<char *, int>("司令4", 122));
    mymap.insert(pair<char *, int>("司令2", 11));
    mymap.insert(pair<char *, int>("司令3", 13));
    mymap.insert(pair<char *, int>("司令4", 123));
    mymap.insert(pair<char *, int>("司令4", 124));

    for (auto i : mymap)
    {
        cout << i.first << " " << i.second << endl;
    }
    cout << endl;

    auto it = mymap.equal_range("司令4");
    for (auto ib = it.first, ie = it.second; ib != ie; ib++)
    {
        cout << (*ib).first << " " << (*ib).second << endl;
    }
    cout << endl;

    system("pause");
    return 0;
}

    

  3.10 哈希映射( hash_map ):是unordered_map的前身

#define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS
#include <iostream>
#include <hash_map>
#include <string>
using namespace std;

//增刪查改與map同樣,本質是哈希表
int main()
{
    hash_map<string, double> mymap{ { "good",120.32 },{ "better",150.89 },{ "best",218.56 },{ "hello",75.36 },{ "kitty",187.85 } };
    mymap.insert(pair<string, double>("love", 356.71));                    //插入
    mymap.insert(hash_map<string, double>::value_type("like", 289.48));    //插入

    for (auto i : mymap)
    {
        cout << i.first << "   " << i.second << endl;
    }
    cout << endl;

    auto it = mymap.find("hello");        //查找
    if (it != mymap.end())
    {
        cout << it->second << endl;
    }

    /*顯示哈希表*/
    for (int i = 0; i < mymap.bucket_count(); i++)                   //打印整個哈希表(按bucket打印),可見unordered_set不容許重複,
    {                                                                //而unordered_multiset容許重複
        cout << "bucket:" << i << ":  ";
        for (auto it = mymap.begin(i); it != mymap.end(i); it++)
        {
            cout << " " << it->first << " " << it->second;
        }
        cout << endl;
    }

    system("pause");
    return 0;
}

    

   3.11 映射( unordered_map ):==> 不容許重複 <==> 哈希表實現

    若要求綜合性能,選:map

    若要求最高查詢性能,選:unordered_map

#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;

//增刪查改與map同樣,本質是哈希表
int main()
{
    unordered_map<string, double> mymap{ {"good",120.32},{"better",150.89},{"best",218.56},{"hello",75.36},{"kitty",187.85} };
    mymap.insert(pair<string, double>("love", 356.71));                        //插入
    mymap.insert(unordered_map<string, double>::value_type("like",289.48));    //插入

    for (auto i : mymap)
    {
        cout << i.first << "   " << i.second << endl;
    }
    cout << endl;

    auto it = mymap.find("hello");        //查找
    if (it != mymap.end())
    {
        cout << it->second << endl;
    }

    /*顯示哈希表*/
    for (int i = 0; i < mymap.bucket_count(); i++)                   //打印整個哈希表(按bucket打印),可見unordered_set不容許重複,
    {                                                                //而unordered_multiset容許重複
        cout << "bucket:" << i << ":  ";
        for (auto it = mymap.begin(i); it != mymap.end(i); it++)
        {
            cout << " " << it->first<<" "<<it->second;
        }
        cout << endl;
    }

    system("pause");
    return 0;
}

    

   3.12 映射( unordered_multimap ):==> 容許重複 <==> 哈希表實現

#include <iostream>
#include <unordered_map>
#include <string>
#include <algorithm>
using namespace std;

//增刪查改與map同樣,本質是哈希表,容許重複
int main()
{
    unordered_multimap<string, double> mymap{ { "good",120.32 },{ "better",150.89 },{ "best",218.56 } };
    mymap.insert(pair<string, double>("love", 356.71));                            //插入
    mymap.insert(pair<string, double>("love", 218.34));
    mymap.insert(pair<string, double>("love", 568.45));
    mymap.insert(unordered_map<string, double>::value_type("like", 289.48));    //插入

    for (auto i : mymap)
    {
        cout << i.first << "   " << i.second << endl;
    }
    cout << endl;

    auto it = mymap.find("hello");        //查找
    if (it != mymap.end())
    {
        cout << it->second << endl;
    }

    /*顯示哈希表*/
    for (int i = 0; i < mymap.bucket_count(); i++)                    //打印整個哈希表(按bucket打印),可見unordered_set不容許重複,
    {                                                                //而unordered_multiset容許重複
        cout << "bucket:" << i << ":  ";
        for (auto it = mymap.begin(i); it != mymap.end(i); it++)
        {
            cout << " " << it->first << " " << it->second;
        }
        cout << endl;
    }
    cout << endl;

    auto itx = mymap.equal_range("love");
    for_each(itx.first, itx.second, [](unordered_multimap<string, double>::value_type &x) {cout << x.first << " " << x.second << endl; });

    system("pause");
    return 0;
}

    

  3.13 用於計算的 valarray:

#include <iostream>
#include <valarray>    //用於計算,計算的性能高於vector,array
#include <iomanip>
using namespace std;

int main()
{
    const double PI = 3.1415926535;
    
    valarray<double> val(9);
    for (int i = 0; i < 9; i++)
    {
        val[i] = PI*i*i;
        cout << val[i] << endl;
    }

    valarray<double> valx(9);
    for (int i = 0; i < 9; i++)
    {
        valx[i] = cos(i*PI / 3);    //能夠直接進行科學計算cos()
        cout << valx[i] << endl;
    }

    valarray<char *> my;    //擁有數組的全部功能,長處是計算

    system("pause");
    return 0;
}

    

 4. 容器小結:

相關文章
相關標籤/搜索