STL基礎學習筆記

  1. set
    set是實現紅黑樹的平衡二叉檢索樹的數據結構,插入元素時,它會自動調整二叉樹的排列。
    set常用操作:
    begin(),返回set容器的第一個元素(*)
    end(),返回set容器的最後一個元素(*)//end()是指向最後一個元素的後一個位置
    clear(),刪除set容器中的所有的元素
    empty(),判斷set容器是否爲空
    max_size(),返回set容器可能包含的元素最大個數
    size() ,返回當前set容器中的元素個數
    insert(),向set中插入某個元素
    lower_bound(x) ,返回第一個大於等於x的定位器位置(*)
    upper_bound(x),返回第一個大於x的定位器位置(*)
    find(),返回給定值值的定位器,如果沒找到則返回end().

代碼實現:

2 . map 與set操作基本類似,只是map類似與一個映射。查找的複雜度基本是Log(N)
常見:
begin() 返回指向map頭部的迭代器
clear() 刪除所有元素
count() 返回指定元素出現的次數
empty() 如果map爲空則返回true
end() 返回指向map末尾的迭代器
erase() 刪除一個元素
find() 查找一個元素
insert() 插入元素
lower_bound() 返回鍵值>=給定元素的第一個位置
max_size() 返回可以容納的最大元素個數
size() 返回map中元素的個數
swap() 交換兩個map(兩個map中所有元素的實現)
upper_bound() 返回鍵值>給定元素的第一個位置

以上常見摘自http://www.cnblogs.com/fnlingnzb-learner/p/5833051.html
代碼實現:

#include<iostream>
#include<map>
using namespace std;
map<int,string>h;
int main()
{
    h.insert(pair<int,string>(1,"ONE"));    //利用pair插入 
    h.insert(map<int, string>::value_type(2,"TWO"));    //利用value_type插入
    h[3]="THREE",h[4]="FOR"; //利用數組形式插入 ,可以覆蓋原來的值
    map<int,string>::iterator it;
    for(it=h.begin();it!=h.end();it++)
    {
        if(it->first==1)
        cout<<it->first<<" "<<it->second<<endl;     
    }
    int nsize=h.size(); //當前已插入了多少元素 
    for(int i=1;i<=nsize;i++)
        cout<<h[i]<<" ";    
    it=h.find(1);
    if(it!=h.end()) cout<<"ok"<<endl;
    it=h.lower_bound(2), cout<<it->second<<endl;
    it=h.upper_bound(2),cout<<it->second<<endl;
    it=h.find(1);
    h.erase(it);//刪除it指向的<int,string>
    it=h.lower_bound(1);
    cout<<endl<<it->second<<endl;
    it=h.upper_bound(1);
    cout<<endl<<it->second<<endl;    h.erase(h.begin(),h.end());//相當於h.clear(); 
    return 0;
}

3.string
因爲考了個題,卡讀入,賊噁心。需要用到string的奇怪姿勢。
erase:
erase(p,n); 刪除從p開始的n個字符(包括p這個位置開始)
erase(it);刪除it這個位置的一個字符(it是個迭代器)
erase(sta,end);刪除從sta到end之間的字符(sta和end都是迭代器)
刪除後會自動調整位置。
find:
find函數的可用來做字符串的包含關係,如果字符串存在包含關係,返回值就是匹配的首字母在原串中的位置,否則會返回-1。
insert:
insert(it,’* * ‘)就是可以在it指向的這個位置插入一個單個字符* *,後面的會後移。
substr:
substr(pos,n)從第pos位開始,截取n位。

代碼:

#include <iostream>
#include <string>
using namespace std;
string str ("where there is a will,there is a way.");
string::iterator it;
int main ()
{
    str.erase(0,1);
    cout<<str<<endl;
    it=str.begin()+6;
    str.erase (it);
    cout<<str<<endl;
    str.erase(str.begin()+6, str.end()-6);
    cout<<str<<endl;
    it=str.begin()+2;
    str.insert(it,'P');
    cout<<str<<endl;
    cout<<str.find("way.")<<endl;
    if(str.find("way.")==-1)    cout<<"no"<<endl;
    else    cout<<"yes"<<endl;
    if(str.find("hello ")==-1)  cout<<"no"<<endl;
    else    cout<<"yes"<<endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章