【STL】-list的用法

初始化ios

#include <list>算法

list<char> clist;spa

算法:code

clist.push_back(c);blog

clist.remove('d');rem

代碼:it

 

 1 #include <list>
 2 #include <iostream>
 3 #include <iterator>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 int main() 
 8 {
 9     list<char> clist;
10 
11     //can't put iter initialization here
12     //because clist is empty now, iter will be NULL
13     //list<char>::iterator iter = clist.begin();    
14     
15     for(char c = 'a'; c < 'f'; ++c)
16         clist.push_back(c);
17 
18     list<char>::iterator iter = clist.begin();    
19 
20     for(; iter != clist.end(); ++iter)
21         cout << *iter << " | ";
22 
23     cout << endl;
24 
25     //高效率remove,利用list特色,只移動一個元素
26     clist.remove('d');
27     copy(clist.begin(), clist.end(), ostream_iterator<char>(cout, " "));
28 
29     cout << endl;
30 
31     //低效率remove, 算法,須要移動不少元素
32     clist.erase(remove(clist.begin(), clist.end(), 'c'), clist.end());
33     copy(clist.begin(), clist.end(), ostream_iterator<char>(cout, " "));    
34 
35     return 0;
36 }

 

 

 

輸出:io

 

$ ./a.exe
a | b | c | d | e |
a b c e
a b e
相關文章
相關標籤/搜索