1. 程式人生 > >STL之set具體解釋(二)

STL之set具體解釋(二)

基本操作 二叉樹 mono itl 自己 pair leading 左右子樹 ews

首先來看看set集合容器:

set集合容器實現了紅黑樹的平衡二叉樹數據結構。在插入元素時它會自己主動調整二叉樹的排列,把該元素放到適當的位置,而且

保證左右子樹平衡。平衡二叉檢索樹採用中序遍歷算法。

對於set,vector,map等等,它們的前向叠代器定義是這種(以set為例):

set<int>::iterator it;

for(it=s.begin();it!=s.end();it++){}

那麽反向叠代器呢?

set<int>::reverse_iterator rit;

for(rit=s.rbegin();rit!=s.rend();rit++){}

經常用法:insert(),erase(),find(),clear()

find()方法是查找元素方法。假設找到就返回該元素叠代器的位置,否則就返回最後一個元素後面的一個位置。

這樣來使用:

it=s.find(5);

if(it!=s.end()) {}

else {}

關於比較函數:

假設元素不是結構體。而是基本數據類型,那麽就自定義一個比較函數:

[cpp] view plaincopy
  1. struct cmp
  2. {
  3. bool operator()(const int &a,
    const int &b)
  4. {
  5. return a>b;
  6. }
  7. };
  8. int main()
  9. {
  10. set<int,cmp> s;
  11. for(int i=1;i<10;i++)
  12. s.insert(i);
  13. set<int,cmp>::iterator it;
  14. for(it=s.begin();it!=s.end();it++)
  15. cout<<*it<<" ";
  16. return 0;
  17. }


假設元素是結構體,那麽比較函數直接能夠寫在結構體裏面。

[cpp] view plaincopy
  1. struct Student
  2. {
  3. string name;
  4. double score;
  5. bool operator < (const Student &a) const
  6. {
  7. return a.score<score;
  8. }
  9. };
  10. set<Student> s;


對於set容器來說。它不能有keyword同樣的元素同一時候存在,假設要保留同樣的元素,就用multiset多重集合容器。

其基本操作跟set集合容器幾乎相同一樣。定義方法是:multiset<string> ms;

map映照容器:

map映照容器的元素數據是由一個鍵值和一個映照數據組成的,鍵值與映照數據之間具有一一相應關系。

map也是用紅黑樹實現

的。

同set一樣,map不同意插入元素鍵值同樣,而multimap多重應照集合能夠同意鍵值反復。

用法:

[cpp] view plaincopy
  1. int main()
  2. {
  3. map<string,double> m;
  4. m["Jack"]=98.0;
  5. map<string,double>::iterator it;
  6. for(it=m.begin();it!=m.end();it++)
  7. cout<<(*it).first<<" "<<(*it).second<<endl;
  8. return 0;
  9. }


主要方法有:insert(),clear(),erase(),find()等等,基本跟set一樣。對於multimap用法跟map幾乎相同一樣。

std::pair基本的作用是將兩個數據組合成一個數據,兩個數據能夠是同一類型或者不同類型。

比如 std::pair<int,float> 或者 std::pair<double,double>等。

pair實質上是一個結構體。其基本的兩個成員變量

是first和second。這兩個變量能夠直接使用。

初始化一個pair能夠使用構造函數,也能夠使用std::make_pair函數。

make_pair函數的定義例如以下:

[cpp] view plaincopy
  1. template pair make_pair(T1 a, T2 b)
  2. {
  3. return pair(a, b);
  4. }


所以m.insert(pair<string,double>("Luce",88.5));

與 m.insert(make_pair("Luce",88.5)); 是相同的效果。

演示樣例:

[cpp] view plaincopy
  1. int main()
  2. {
  3. typedef pair<string,double> lesson;
  4. typedef multimap<string,lesson> stu;
  5. stu a;
  6. a.insert(make_pair("Jack",lesson("math",90.5)));
  7. a.insert(make_pair("Jack",lesson("history",85.5)));
  8. a.insert(make_pair("Luce",lesson("math",99.0)));
  9. map<string,lesson>::iterator it;
  10. for(it=a.begin();it!=a.end();it++)
  11. cout<<(*it).first<<" "<<(*it).second.first<<" "<<(*it).second.second<<endl;
  12. return 0;
  13. }

STL之set具體解釋(二)