2018年3月12日 星期一

程式設計I -- 集合(set)

使用set前要先引入
#include<set>


1. 宣告set


set<int> buf;
宣告一個名字是 buf 的 set , 裏面每個元素都是整數


set<intbuf1 = {1, 2, 3}; 


宣告一個名字是 buf1 的 set , 初始時 , 包含 1, 2, 3
注意:作法只能用於 C++11


2. Set 的新增
set<intbuf;
buf.insert(15)
buf.insert(8)
buf.insert(15)
buf.insert(7)
for(int v:buf)
cout << v << endl;
新增 15 到 buf 中
注意:當新增的數,已經存在於Set中時,就不會新增進入set,set中的值不會重複。
注意:會由小到大排序
輸出:
  • 7
    8
    15

3. Set 的刪除
set<intbuf1 = {1, 2, 3}; 
buf1.erase(2)

輸出:
  • 1
    3
    
  • 
    
4. Set 的走訪
---方法一---(簡單的走訪)
set<int> buf = { 1, 3, 7 };
for (int v : buf)
        cout << v << endl;

輸出:
  • 1
    3
    7
    
    
---方法二---(使用迭代器)
set<int> buf = { 1, 3, 7 };
for (set<int>::iterator it = buf.begin(); it !=buf.end(); it++)
cout << *it << endl;

解釋:it 可以視為嚮導它的專屬的名字叫迭代器,最初嚮導由 begin() 開始,只要嚮導還沒有走到尾巴 (end()) ,嚮導走訪下一個元素
解釋:
it 是嚮導的位置
*it 是嚮導位置的內容(值)

5. 在 set 中找某個元素在不在
---方法一---(find())
set<int> c = { 18, 27, 39 };
if (c.find(19) == c.end())
cout << "沒找到" << endl;
else
cout << "找到" << endl;

輸出:
  • 沒找到
    
解釋:
find 會在 c 中由開始 (begin() ) 找到尾巴 ( end() )。
如果沒找到,就會停在 end() 的地方

---方法二---(count())
set<int> c = { 18, 27, 39 };
if (c.count(18) == 0)
cout << "沒找到" << endl;
else
cout << "找到" << endl;
輸出:
  • 找到
    
    
解釋:
Count 會計算出現的次數
有出現      count() 回傳 1
沒有出現  count() 回傳 0




沒有留言:

張貼留言