STL

vector

定義

#include<vector>
using namespace std;
vector<數據類型>數組名稱

方法總結

push_back()   在末尾加入一個元素
pop_back()     在末尾彈出一個元素
size()		   獲取長度
clear()			清空

- 高級用法
1.不僅可以放基本的數據結構,還可以存儲自定義數據類型,例如結構體等等。
2.構造函數

int n=10;
vector<int>a(n,1);

這段代碼調用了構造函數,第一個參數表示動態數組的長度,第二個參數表示數組裏面每個元素的值,如果不傳入第二個參數那麼初始值爲0。

二維動態數組
定義:

vector<vector<int> >a;

快速構造一個n行m的動態數組

vector<vector<int> >a(n,vector<int>(m,0));
//此處的初始值爲0

集合set

定義

#include<set>
using namespace std;
set<string>a;
//定義了一個string類型的集合a

方法

insert()	插入一個元素		O(log n)
erase()		刪除一個元素		O(log n)
count()		統計集合中某個元素的個數 O(log n)	
size()		獲取元素個數		O(1)
clear()		清空			O(n)

遍歷元素
c++可以通過迭代器訪問集合的每個元素。通過*操作可以獲取迭代器指向的元素。通過++,–可以指向上(下)一個元素。
寫法:set<int>::iterator it
begin函數返回容器中起始元素的迭代器,end函數返回容器的尾後迭代器。

#include <set>
#include <string>
#include <iostream>
using namespace std;
int main() {
    set<string> country;  
    country.insert("China"); 
    country.insert("America"); 
    country.insert("France"); "America", "France"}
    for (set<string>::iterator it = country.begin(); it != country.end(); it++) {
        cout << *it << endl;
    }
    return 0;
}

在這裏插入圖片描述
set中的元素不會重複,set自帶排序。
結構體集合
由於set自帶排序,所以使用結構體set時,要在結構體裏面定義一個重載了小於符號的

#include <iostream>
#include <set>
using namespace std;
struct Point{
    int x,y;
    bool operator<(const Point &rhs)const{
        if(x==rhs.x){
            return y<rhs.y;
        }else {
            return x<rhs.x;
        }
    }
};
int main() {
    int n;
    set<Point> v;
    cin>>n;
    for(int i=0;i<n;i++){
        Point temp;
        cin>>temp.x>>temp.y;
        v.insert(temp);
    }
    for(set<Point>::iterator it = v.begin();it!=v.end();it++){
        cout<<it->x<<" "<<it->y<<endl;
    }
        
    return 0;
}

例如這樣,< 表示要重載的運算符,以上代碼表示優先x從小到大排序,如果x相同,那麼再按照y從小到大排序。

bool operator<(const Point &rhs)const

映射map

定義:

#include<set>
using namespace std;
set<t1,t2>a;

方法

inset()		插入一對映射		O(log n)
count()		判斷關鍵詞是否存在	O(log n)
size()		獲取映射對的個數		O(1)
clear()		清空 O(n)

插入一對映射
insert()函數的參數是一個pair
pair定義在頭文件utility裏面,可以看成是有兩個成員變量first,second的結構體,並且重載了<運算符(先比較first的大小,再比較second)。make_pair(v1,v2)函數返回由v1,v2,初始的pair

#include <map>
#include <string>
#include <utility>
using namespace std;
int main() {
    map<string, int> dict;              // dict 是一個 string 到 int 的映射,存放每個名字對應的班級號,初始時爲空
    dict.insert(make_pair("Tom", 1));   // {"Tom"->1}
    dict.insert(make_pair("Jone", 2));  // {"Tom"->1, "Jone"->2}
    dict.insert(make_pair("Mary", 1));  // {"Tom"->1, "Jone"->2, "Mary"->1}
    dict.insert(make_pair("Tom", 2));   // {"Tom"->1, "Jone"->2, "Mary"->1}
    return 0;
}

dict.insert(make_pair(“Tom”, 1)); 這句話也可以直接用下表表示,dict[“Tom”]=1,這樣用下標的方式更常見。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章