1. 程式人生 > >STL 中常用的 vector,map,set,sort 用法

STL 中常用的 vector,map,set,sort 用法

STL中的常用的vector,map,set,sort,pair用法

C++的標準模板庫(Standard Template Library,簡稱STL)是一個容器和演算法的類庫。容器往往包含同一型別的資料。STL中比較常用的容器是vector,set和map,比較常用的演算法有Sort等。
.
一. vector 1.宣告:
一個vector類似於一個動態的一維陣列。
           vector中可以存在重複的元素! vector<int> a;          // 宣告一個元素為int型別的vector a            vectot<MyType> a;       // 宣告一個元素為MyType型別的vector a
這裡的宣告的a包含0個元素,既a.size()的值為0,但它是動態的,其大小會隨著資料的插入
和刪除改變而改變。
vector<int> a(100, 0);  // 這裡宣告的是一個已經存放了100個0的整數vector 2.向量操作
常用函式:
          a.size();                // 返回vector的大小,即包含的元素個數
          a.pop_back();            // 刪除vector末尾的元素,vector大小相應減一
          a.push_back();           // 用於在vector的末尾新增元素
          a.back();                // 返回vector末尾的元素
          a.clear();               // 將vector清空,vector大小變為0
其他訪問方式:
          cout<<a[5]<<endl;
          cout<<a.at(5)<<endl;
以上區別在於後者在訪問越界時會丟擲異常,而前者不會。
3.遍歷           (1).     for(vector<datatype>::iterator it=a.begin(); it!=a.end(); it++)                      cout<<*it<<endl;           (2).     for(int i = 0; i < a.size(); i++)                      cout<<a[i]<<endl;
1.vector 的資料的存入和輸出:
#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
	int i = 0;
    vector<int> v;
    for(i = 0; i < 10; i++)
	{
		v.push_back( i );       //把元素一個一個存入到vector中
	}
    /* v.clear()*/ //對存入的資料清空
	for( i = 0; i < v.size(); i++ ) //v.size() 表示vector存入元素的個數
	{
		cout << v[ i ] << "  "; //把每個元素顯示出來
	}
	cout << endl;
}


1. push_back()        在陣列的最後新增一個數據
2. pop_back()         去掉陣列的最後一個數據
3. at()               得到編號位置的資料
4. begin()            得到陣列頭的指標
5. end()              得到陣列的最後一個單元+1的指標
6. front()            得到陣列頭的引用
7. back()             得到陣列的最後一個單元的引用
8. max_size()         得到vector最大可以是多大
9. capacity()         當前vector分配的大小
10.size()             當前使用資料的大小
11.resize()           改變當前使用資料的大小,如果它比當前使用的大,則填充預設值
12.reserve()          改變當前vecotr所分配空間的大小
13.erase()            刪除指標指向的資料項
14.clear()            清空當前的vector
15.rbegin()           將vector反轉後的開始指標返回(其實就是原來的end-1)
16.rend()             將vector反轉構的結束指標返回(其實就是原來的begin-1)
17.empty()            判斷vector是否為空
18.swap()             與另一個vector交換資料
二. map Map是STL的一個關聯容器,它提供一對一(其中第一個可以稱為關鍵字,每個關鍵字只能在map中出現一次,第二個可能稱為該關鍵字的值)的資料處理能力,由於這個特性
map內部的實現自建一顆紅黑樹(一種非嚴格意義上的平衡二叉樹),這顆樹具有對資料自動排序的功能。
下面舉例說明什麼是一對一的資料對映。比如一個班級中,每個學生的學號跟他的姓名就存在著一一對映的關係,這個模型用map可能輕易描述,
很明顯學號用int描述,姓名用字串描述(本篇文章中不用char *來描述字串,而是採用STL中string來描述),
下面給出map描述程式碼:

1.宣告方式:
           map<int, string> mapStudent; 或map<string,int> mapStudent; 
/*兩者均是正確宣告方式,當然效果是不一樣的*/ 2.資料的插入
在構造map容器後,我們就可以往裡面插入資料了。這裡講三種插入資料的方法:
第一種:用insert函式插入pair資料
           map<int, string> mapStudent;
           mapStudent.insert(pair<int, string>(1,“student_one”));
第二種:用insert函式插入value_type資料
           map<int, string> mapStudent;
           mapStudent.insert(map<int, string>::value_type (1,"student_one"));
   mapStudent.insert(make_pair(1, "student_one"));
第三種:用陣列方式插入資料
           map<int, string> mapStudent;
           mapStudent[1] = “student_one”;
           mapStudent[2] = “student_two”;
/*
如果是
#include <map>
map<string, int> mapStudent;
string s;
插入就用m[s]++;

*/
以上三種用法,雖然都可以實現資料的插入,但是它們是有區別的,當然了第一種和第二種在效果上是完成一樣的,用insert函式插入資料,在資料的插入上涉及到集合的唯一性這個概念,即當map中有這個關鍵字時,insert操作是不能再插入這個資料的,但是用陣列方式就不同了,它可以覆蓋以前該關鍵字對應的值; 3.map的大小 在往map裡面插入了資料,我們怎麼知道當前已經插入了多少資料呢,可以用size函式:
             int nSize = mapStudent.size();

4.資料的遍歷
第一種:應用前向迭代器
map<int, string>::iterator iter;
for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
    cout<<iter->first<<"  "<<iter->second<<end;



第二種:應用反向迭代器
map<int, string>::reverse_iterator iter;
for(iter = mapStudent.rbegin(); iter != mapStudent.rend(); iter++)
    cout<<iter->first<<"  "<<iter->second<<end;



第三種:用陣列方式
 
int nsize = mapStudent.size()
for(int nIndex = 1; nIndex <= nSize; nIndex++)
     cout<<mapStudent[nIndex]<<end;



例如:
#include<map>
#include<string>
#include<iostream>
using namespace std;

int main()
{
    map<string,int>  m;
    m["a"]=1;
    m["b"]=2;
    m["c"]=3;
    map<string,int>::iterator it;
    for(it=m.begin();it!=m.end();++it)
        cout<<"key: "<<it->first <<" value: "<<it->second<<endl;
    return   0;
}

 
map<string,int>::iterator it;   定義一個迭代指標it。 
it->first 為索引鍵值,it->second 為值。


5. 資料的查詢(包括判定這個關鍵字是否在map中出現) 這裡給出三種資料查詢方法:
第一種:用count函式來判定關鍵字是否出現,但是無法定位資料出現位置
第二種:用find函式來定位資料出現位置它返回的一個迭代器,
當資料出現時,它返回資料所在位置的迭代器,如果map中沒有要查詢的資料,它返回的迭代器等於end函式返回的迭代器。
例如:
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中不出現這個關鍵字,程式說明
mapPair = mapStudent.equal_range(2);
if(mapPair.first == mapPair.second)
      
            cout<<”Do not Find”<<endl;

6. 資料的清空與判空
清空map中的資料可以用clear()函式,判定map中是否有資料可以用empty()函式,它返回true則說明是空map
7. 資料的刪除
這裡要用到erase函式,它有三個過載了的函式
迭代器刪除 
            iter = mapStudent.find(1);
            mapStudent.erase(iter);
用關鍵字刪除
            int n = mapStudent.erase(1);//如果刪除了會返回1,否則返回0
用迭代器,成片的刪除
            一下程式碼把整個map清空
            mapStudent.earse(mapStudent.begin(), mapStudent.end());
            //成片刪除要注意的是,也是STL的特性,刪除區間是一個前閉後開的集合

8.其他一些函式用法
這裡有swap,key_comp,value_comp,get_allocator等函式; 例如: map <int, vector<int> > mm; 第二個鍵值是一個vector容器,就可以存多個值,和二維陣列a[ ] [ ],差不多了! 個數 : int len = mm[tt].size(); 訪問其中的值,直接可以用mm[i] [j]訪問; vector<int> ::iterator iter; iter = lower_bound(mm[tt].begin(), mm[tt].end(), l); 三. set set是集合,set中不會包含重複的元素,這是和vector的區別。 定義:
定義一個元素為整數的集合a,可以用 set<int> a;
1,set的含義是集合,它是一個有序的容器,裡面的元素都是排序好的,支援插入,刪除,查詢等操作,就像一個集合一樣。所有的操作都是嚴格在logn時間之內完成的,效率非常高。 set和multiset的區別是:set插入的元素不能相同,但是multiset可以相同。 set的基本操作:
1. begin()         返回指向第一個元素的迭代器
2. clear()         清除所有元素
3. count()         返回某個值元素的個數
4. empty()         如果集合為空,返回true
5. end()           返回指向最後一個元素的迭代器
6. equal_range()   返回集合中與給定值相等的上下限的兩個迭代器
7. erase()         刪除集合中的元素
8. find()          返回一個指向被查詢到元素的迭代器
9. get_allocator() 返回集合的分配器
10.insert()        在集合中插入元素
11.lower_bound()   返回指向大於(或等於)某值的第一個元素的迭代器
12.key_comp()      返回一個用於元素間值比較的函式
13.max_size()      返回集合能容納的元素的最大限值
14.rbegin()        返回指向集合中最後一個元素的反向迭代器
15.rend()          返回指向集合中第一個元素的反向迭代器
16.size()          集合中元素的數目
17.swap()          交換兩個集合變數
18.upper_bound()   返回大於某個值元素的迭代器
19.value_comp()    返回一個用於比較元素間的值的函式
set的遍歷 程式碼如下:
set<int>ss;
        set<int>::iterator it;
        for(it = ss.begin(); it != ss.end(); it++)
        {
            printf("%d ",*it);
        }


lower_bound()返回一個 iterator 它指向在[first,last)標記的有序序列中可以插入value,而不會破壞容器順序的第一個位置,而這個位置標記了一個大於等於value 的值。   例如,有如下序列:  ia[]={12,15,17,19,20,22,23,26,29,35,40,51}; 用值21呼叫lower_bound(),返回一個指向22的iterator。用值22呼叫lower_bound(),也返回一個指向22的iterator。 iterator upper_bound( const key_type &key ):返回一個迭代器,指向鍵值> key的第一個元素。 -------------------------------------------------------------------------------------------------

函式lower_bound()在first和last中的前閉後開區間進行二分查詢,返回大於或等於val的第一個元素位置。如果所有元素都小於val,則返回last的位置

舉例如下:

一個數組number序列為:4,10,11,30,69,70,96,100.設要插入數字3,9,111.pos為要插入的位置的下標

pos = lower_bound( number, number + 8, 3) - number,pos = 0.即number陣列的下標為0的位置。

pos = lower_bound( number, number + 8, 9) - number, pos = 1,即number陣列的下標為1的位置(即10所在的位置)。

pos = lower_bound( number, number + 8, 111) - number, pos = 8,即number陣列的下標為8的位置(但下標上限為7,所以返回最後一個元素的下一個元素)。

所以,要記住:函式lower_bound()在first和last中的前閉後開區間進行二分查詢,返回大於或等於val的第一個元素位置。如果所有元素都小於val,則返回last的位置,且last的位置是越界的!!~

返回查詢元素的第一個可安插位置,也就是“元素值>=查詢值”的第一個元素的位置

-------------------------------------------------------------------------------------------------
集合的並,交和差
set_union(a.begin(),a.end(),b.begin(),b.end(),insert_iterator<set<int> >(c,c.begin()));
set_intersection(a.begin(),a.end(),b.begin(),b.end(),insert_iterator<set<int> >(c,c.begin()));
set_difference(a.begin(),a.end(),b.begin(),b.end(),insert_iterator<set<int> >(c,c.begin()));
(注意在此前要將c清為空集)。
注意:
為了實現集合的快速運算,set的實現採用了平衡二叉樹,因此,set中的元素必須是可排序的。如果是自定義的型別,那在定義型別的同時必須給出運算子<的定義
struct node
{
    int x, y;
    bool operator < (const struct node tmp) const
    {
        if(x == tmp.x)
            return y < tmp.y ;
        return x < tmp.x ;
    }
} ;
四. Sort sort顧名思義就是排序
用法:
單關鍵字:
                 對於vector a來說
                 sort(a,a+n); //n=a.size()       將a中元素按遞增排序。
多關鍵字:
                 我們也可以利用類pair
                 vector< pair<int,int> > a; // 注意這裡兩個> >中間必須有一個空格,否則編譯器會當是運算子>>
例如:
int N,x,y;
cin >> N;
for(int i = 0; i < N; ++i) 
{
	cin >> x >> y;
	a.push_back(make_pair(x,y)); // make_pair用於建立pair物件
}
sort(&a[0], &a[N]);</span>
注意:
對於我們自己定義的類或結構,系統一般不能做比較運算,需要我們自己定義相應的運算子

bool cmp(MyType x, MyType y)
{
	if(x < y)
		return true;
	if(x >= y)
		return false;
}


map是一個關聯容器,裡面存放的是鍵值對,容器中每一元素都是pair型別,通過map的insert()方法來插入元素(pair型別)。template <class T1,class T2>
  pair<T1,T2> make_pair (T1 x, T2 y)
  {
    return ( pair<T1,T2>(x,y) );
  }

pair的型別:

    pair 是 一種模版型別。每個pair 可以儲存兩個值。這兩種值無限制。也可以將自己寫的struct的物件放進去。。

    pair<string,int> p;

    pair<int ,int > p;

    pair<double,int> p;

    都可以。。。  

    std::pair主要的作用是將兩個資料組合成一個數據,兩個資料可以是同一型別或者不同型別。例如std::pair<int,float> 或者 std::pair<double,double>等。pair實質上是一個結構體,其主要的兩個成員變數是first和second,這兩個變數可以直接使用。初始化一個pair可以使用建構函式,也可以使用std::make_pair函式。

應用:如果一個函式有兩個返回值 的話,如果是相同型別,就可以用陣列返回,如果是不同型別,就可以自己寫個struct ,但為了方便就可以使用 c++ 自帶的pair ,返回一個pair,其中帶有兩個值。除了返回值的應用,在一個物件有多個屬性的時候 ,一般自己寫一個struct ,如果就是兩個屬性的話,就可以用pair 進行操作。。。
          應用pair 可以省的自己寫一個struct 。。。如果有三個屬性的話,其實也是可以用的pair 的 ,極端的寫法 pair <int ,pair<int ,int > >寫法極端。(後邊的兩個 > > 要有空格,否則就會是 >> 位移運算子)
    
   pair<int ,int >p (5,6);
   pair<int ,int > p1= make_pair(5,6);
   pair<string,double> p2 ("aa",5.0);
   pair <string ,double> p3 = make_pair("aa",5.0);
   有這兩種寫法來生成一個pair。
   如何取得pair的值呢。。
   每個pair 都有兩個屬性值 first 和second    cout<<p1.first<<p1.second; 注意是屬性值而不是方法。

      一般make_pair都使用在需要pair做引數的位置,可以直接呼叫make_pair生成pair物件。make_pair是根據2個引數型別推匯出pair的2個模板引數型別的。另一個使用的方面就是pair可以接受隱式的型別轉換,這樣可以獲得更高的靈活度。但是這樣會出現如下問題:例如有如下兩個定義:

<span style="font-size:18px;">std::pair<int, float>(1, 1.1);
std::make_pair(1, 1.1);
</span>

     其中第一個的second變數是float型別,而make_pair函式會將second變數都轉換成double型別。這個問題在程式設計是需要引起注意。下面是一段pair與make_pair的例子程式:

#include <iostream>
#include <utility>
#include <string>
using namespace std;
int main ()
{
        pair <string,double> product1 ("tomatoes",3.25);
	pair <string,double> product2;
	pair <string,double> product3;

	product2.first ="lightbulbs"; // type of first is string
	product2.second =0.99; // type of second is double
	
	product3 = make_pair ("shoes",20.0);
		
	cout <<"The price of "<< product1.first <<" is $"<< product1.second <<"\n";
	cout <<"The price of "<< product2.first <<" is $"<< product2.second <<"\n";
	cout <<"The price of "<< product3.first <<" is $"<< product3.second <<"\n";
	return 0;
}


map是一個關聯容器,裡面存放的是鍵值對,容器中每一元素都是pair型別,通過map的insert()方法來插入元素(pair型別)。

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

mapStudent.insert(make_pair(1, "student_one"));