Overview
Ping-Lun Liao
S T
L
Outline
STL
Container
Iterator
Algorithm
Function Object
What is STL
Standard Template Library.
ANSI/ISO C++
Key Person
Alexander A. Stepanov
STL 的不同實現版本
HP STL :這是第一個版本
P.J. Plauger STL
Rouge Wave STL
SGI STL
STLport
Reference:
C++ STL編程輕鬆入門基礎 1.4節
Why do we learn STL
 第一版:史前時代 -- 轉木取火
 採用大容量的靜態數組分配。
 限定輸入的數據個數。
 採用動態內存分配。
 第二版:工業時代 -- 組件化大生產
 第三版:唯美主義的傑作
 Demo
Short Talk About STL
 Container( 容器 ) :各種資料結構如 vector 、 li
st 、 deque 、 set 、 map 。
 Algorithm :各種常見的演算法如 sort 、 search
、 copy 、 erase… 等。
 Iterators( 迭代器 ) :扮演容器與演算法之間的
膠著劑,所謂的「泛型指標」。
 Functors( 仿函式 ) :行為類似函式,可做為演
算法的某種策略 (policy) 。
 Adapters( 配接器 ) :一種用來修飾容器或仿函
式或迭代器介面的東西,如 stack 。
 Allocators( 配置器 ) :負責空間配置與管理。
這不是賞心悅目的圖
Container
Three types of containers
Sequence containers
Linear data structures (vectors, linked lists)
First-class container
Associative containers
Non-linear, can find elements quickly
Key/value pairs
First-class container
Container adapters
STL Container Classes
 Sequence containers
 vector
 deque
 list
 Associative containers
 set
 multiset
 map
 multimap
 Container adapters
 stack
 queue
 priority_queue
Sequence Containers
Three sequence containers
vector - based on arrays
deque - based on arrays
list - robust linked list
vector
 vector
<vector>
Data structure with contiguous memory locations
Access elements with []
Use when data must be sorted and easily accessible
 When memory exhausted
Allocates larger, contiguous area of memory
Copies itself there
Deallocates old memory
 Has random access iterators
list
list container
Header <list>
Efficient insertion/deletion anywhere in contain
er
Doubly-linked list (two pointers per node)
Bidirectional iterators
std::list< type > name;
deque
 deque ("deek"): double-ended queue
Header <deque>
Indexed access using []
Efficient insertion/deletion in front and back
Non-contiguous memory: has "smarter" iterators
 Same basic operations as vector
Also has
push_front (insert at front of deque)
pop_front (delete from front)
Associative containers
Associative containers
Direct access to store/retrieve elements
Uses keys (search keys)
4 types: multiset, set, multimap and map
Keys in sorted order
multiset and multimap allow duplicate keys
multimap and map have keys and associated values
multiset and set only have values
Key
Value
multiset
 multiset
Header <set>
Fast storage, retrieval of keys (no values)
Allows duplicates
Bidirectional iterators
 Ordering of elements
Done by comparator function object
Used when creating multiset
For integer multiset
less<int> comparator function object
multiset< int, std::less<int> > myObject;
Elements will be sorted in ascending order
set
 set
Header <set>
Implementation identical to multiset
Unique keys
Duplicates ignored and not inserted
Supports bidirectional iterators (but not random access)
std::set< type, std::less<type> > name;
multimap
 multimap
Header <map>
Fast storage and retrieval of keys and associated values
Has key/value pairs
Duplicate keys allowed (multiple values for a single ke
y)
One-to-many relationship
I.e., one student can take many courses
Insert pair objects (with a key and value)
Bidirectional iterators
map
 map
Header <map>
Like multimap, but only unique key/value pairs
One-to-one mapping (duplicates ignored)
Use [] to access values
Example: for map object m
m[30] = 4000.21;
Sets the value of key 30 to 4000.21
If subscript not in map, creates new key/value pair
 Type declaration
 std::map< int, double, std::less< int > >;
Container Adapters
Container adapters
stack, queue and priority_queue
Not first class containers
Do not support iterators
Do not provide actual data structure
Programmer can select implementation
Member functions push and pop
stack
 stack
Header <stack>
Insertions and deletions at one end
Last-in, first-out (LIFO) data structure
Can use vector, list, or deque (default)
Declarations
stack<type, vector<type> > myStack;
stack<type, list<type> > myOtherStack;
stack<type> anotherStack; // default deque
vector, list
 Implementation of stack (default deque)
 Does not change behavior, just performance (deque and vect
or fastest)
queue
 queue
 Header <queue>
 Insertions at back, deletions at front
 First-in-first-out (FIFO) data structure
 Implemented with list or deque (default)
 std::queue<double> values;
 Functions
 push( element )
 Same as push_back, add to end
 pop( element )
 Implemented with pop_front, remove from front
 empty()
 size()
priority_queue
 priority_queue
Header <queue>
Insertions happen in sorted order, deletions from front
Implemented with vector (default) or deque
Highest priority element always removed first
Heapsort algorithm puts largest elements at front
less<T> default, programmer can specify other comparator
Functions
push(value), pop(value)
top()
 View top element
size()
empty()
Iterator
 Iterators similar to pointers
Point to first element in a container
Iterator operators same for all containers
* dereferences
++ points to next element
begin() returns iterator to first element
end() returns iterator to last element
Use iterators with sequences (ranges)
Containers
Input sequences: istream_iterator
Output sequences: ostream_iterator
Iterator Categories
 Input
Read elements from container, can only move forward
 Output
Write elements to container, only forward
 Forward
Combines input and output, retains position
Multi-pass (can pass through sequence twice)
 Bidirectional
Like forward, but can move backwards as well
 Random access
Like bidirectional, but can also jump to any element
Example
Here
Algorithms
 STL has algorithms used generically across contai
ners
Operate on elements indirectly via iterators
Often operate on sequences of elements
Defined by pairs of iterators
First and last element
Algorithms often return iterators
find()
Returns iterator to element, or end() if not found
Premade algorithms save programmers time and effort
Before STL
Class libraries incompatible among vendors
Algorithms built into container classes
STL separates containers and algorithms
Easier to add new algorithms
More efficient, avoids virtual function calls
<algorithm>
Algorithms
Function Object (Functor)
 Function objects (<functional>)
Contain functions invoked using operator()
STL function objects Type
divides< T > arithmetic
equal_to< T > relational
greater< T > relational
greater_equal< T > relational
less< T > relational
less_equal< T > relational
logical_and< T > logical
logical_not< T > logical
logical_or< T > logical
minus< T > arithmetic
modulus< T > arithmetic
negate< T > arithmetic
not_equal_to< T > relational
plus< T > arithmetic
multiplies< T > arithmetic
class FunctoinObject
{
public:
template<class T>
T operator() (T t) const{…;};
}
Demo
Function Object (Functor)
Using STL I
 class TMyClass;
 typedef list<TMyClass> TMyClassList;
// 用於存放對象的 list 容器
 typedef list<TMyClass*> TMyClassPtrList; // 用於存放
對象指針的 list 容器
Using STL II
class TMyClass {
private:
...
public:
TMyClass(..); // 拷貝構造函數
TMyClass(const TMyClass& obj)
{ *this = obj; } // 賦值操作符
TMyClass& operator=(const TMyClass& obj); ... };
Using STL III
TMyClass object;
TMyClassList myList;
TMyClassList::iterator it;
it = myList.insert(myList.end(), object);
TMyClass *pObject = &(*it);
Using STL IIII
TMyClassList::iterator it;
TMyClass *pObject;
for (it = myList.begin(); it != myList.end(); it ++)
{ pObject = &(*it); // 使用 pObject }
//pObject = *it;
Using STL V
TMyClassList::iterator it;
TMyClass *pObject;
for (it = myList.begin(); it != myList.end(); it ++)
{
pObject = &(*it);
if (pObject 滿足某些刪除的標註 ) then
myList.erase(it);
// 若 list 裡面保存的是指針,那麼增加下面代碼
delete pObject;
}
Demo
Example
測試結果
範例: Deitel C++ How To Program Ch21
Cl Version 14.00.50727.42 全通過
gcc version 3.4.2 (mingw-special) 十二個
bcc32 九個
Reference
C++ How to Program 3rd.
STL 源碼剖析
STL中文站
建議閱讀書籍
基礎
C++ 程式語言經典增訂版
C++ 標準程式庫
進階
Effective STL
泛型程式設計與 STL
STL 源碼剖析
Q & A
END

C++ STL 概觀

  • 1.
  • 2.
  • 3.
    What is STL StandardTemplate Library. ANSI/ISO C++ Key Person Alexander A. Stepanov
  • 4.
    STL 的不同實現版本 HP STL:這是第一個版本 P.J. Plauger STL Rouge Wave STL SGI STL STLport Reference: C++ STL編程輕鬆入門基礎 1.4節
  • 5.
    Why do welearn STL  第一版:史前時代 -- 轉木取火  採用大容量的靜態數組分配。  限定輸入的數據個數。  採用動態內存分配。  第二版:工業時代 -- 組件化大生產  第三版:唯美主義的傑作  Demo
  • 6.
    Short Talk AboutSTL  Container( 容器 ) :各種資料結構如 vector 、 li st 、 deque 、 set 、 map 。  Algorithm :各種常見的演算法如 sort 、 search 、 copy 、 erase… 等。  Iterators( 迭代器 ) :扮演容器與演算法之間的 膠著劑,所謂的「泛型指標」。  Functors( 仿函式 ) :行為類似函式,可做為演 算法的某種策略 (policy) 。  Adapters( 配接器 ) :一種用來修飾容器或仿函 式或迭代器介面的東西,如 stack 。  Allocators( 配置器 ) :負責空間配置與管理。
  • 7.
  • 8.
    Container Three types ofcontainers Sequence containers Linear data structures (vectors, linked lists) First-class container Associative containers Non-linear, can find elements quickly Key/value pairs First-class container Container adapters
  • 9.
    STL Container Classes Sequence containers  vector  deque  list  Associative containers  set  multiset  map  multimap  Container adapters  stack  queue  priority_queue
  • 10.
    Sequence Containers Three sequencecontainers vector - based on arrays deque - based on arrays list - robust linked list
  • 11.
    vector  vector <vector> Data structurewith contiguous memory locations Access elements with [] Use when data must be sorted and easily accessible  When memory exhausted Allocates larger, contiguous area of memory Copies itself there Deallocates old memory  Has random access iterators
  • 12.
    list list container Header <list> Efficientinsertion/deletion anywhere in contain er Doubly-linked list (two pointers per node) Bidirectional iterators std::list< type > name;
  • 13.
    deque  deque ("deek"):double-ended queue Header <deque> Indexed access using [] Efficient insertion/deletion in front and back Non-contiguous memory: has "smarter" iterators  Same basic operations as vector Also has push_front (insert at front of deque) pop_front (delete from front)
  • 14.
    Associative containers Associative containers Directaccess to store/retrieve elements Uses keys (search keys) 4 types: multiset, set, multimap and map Keys in sorted order multiset and multimap allow duplicate keys multimap and map have keys and associated values multiset and set only have values Key Value
  • 15.
    multiset  multiset Header <set> Faststorage, retrieval of keys (no values) Allows duplicates Bidirectional iterators  Ordering of elements Done by comparator function object Used when creating multiset For integer multiset less<int> comparator function object multiset< int, std::less<int> > myObject; Elements will be sorted in ascending order
  • 16.
    set  set Header <set> Implementationidentical to multiset Unique keys Duplicates ignored and not inserted Supports bidirectional iterators (but not random access) std::set< type, std::less<type> > name;
  • 17.
    multimap  multimap Header <map> Faststorage and retrieval of keys and associated values Has key/value pairs Duplicate keys allowed (multiple values for a single ke y) One-to-many relationship I.e., one student can take many courses Insert pair objects (with a key and value) Bidirectional iterators
  • 18.
    map  map Header <map> Likemultimap, but only unique key/value pairs One-to-one mapping (duplicates ignored) Use [] to access values Example: for map object m m[30] = 4000.21; Sets the value of key 30 to 4000.21 If subscript not in map, creates new key/value pair  Type declaration  std::map< int, double, std::less< int > >;
  • 19.
    Container Adapters Container adapters stack,queue and priority_queue Not first class containers Do not support iterators Do not provide actual data structure Programmer can select implementation Member functions push and pop
  • 20.
    stack  stack Header <stack> Insertionsand deletions at one end Last-in, first-out (LIFO) data structure Can use vector, list, or deque (default) Declarations stack<type, vector<type> > myStack; stack<type, list<type> > myOtherStack; stack<type> anotherStack; // default deque vector, list  Implementation of stack (default deque)  Does not change behavior, just performance (deque and vect or fastest)
  • 21.
    queue  queue  Header<queue>  Insertions at back, deletions at front  First-in-first-out (FIFO) data structure  Implemented with list or deque (default)  std::queue<double> values;  Functions  push( element )  Same as push_back, add to end  pop( element )  Implemented with pop_front, remove from front  empty()  size()
  • 22.
    priority_queue  priority_queue Header <queue> Insertionshappen in sorted order, deletions from front Implemented with vector (default) or deque Highest priority element always removed first Heapsort algorithm puts largest elements at front less<T> default, programmer can specify other comparator Functions push(value), pop(value) top()  View top element size() empty()
  • 23.
    Iterator  Iterators similarto pointers Point to first element in a container Iterator operators same for all containers * dereferences ++ points to next element begin() returns iterator to first element end() returns iterator to last element Use iterators with sequences (ranges) Containers Input sequences: istream_iterator Output sequences: ostream_iterator
  • 24.
    Iterator Categories  Input Readelements from container, can only move forward  Output Write elements to container, only forward  Forward Combines input and output, retains position Multi-pass (can pass through sequence twice)  Bidirectional Like forward, but can move backwards as well  Random access Like bidirectional, but can also jump to any element
  • 25.
  • 26.
    Algorithms  STL hasalgorithms used generically across contai ners Operate on elements indirectly via iterators Often operate on sequences of elements Defined by pairs of iterators First and last element Algorithms often return iterators find() Returns iterator to element, or end() if not found Premade algorithms save programmers time and effort
  • 27.
    Before STL Class librariesincompatible among vendors Algorithms built into container classes STL separates containers and algorithms Easier to add new algorithms More efficient, avoids virtual function calls <algorithm> Algorithms
  • 28.
    Function Object (Functor) Function objects (<functional>) Contain functions invoked using operator() STL function objects Type divides< T > arithmetic equal_to< T > relational greater< T > relational greater_equal< T > relational less< T > relational less_equal< T > relational logical_and< T > logical logical_not< T > logical logical_or< T > logical minus< T > arithmetic modulus< T > arithmetic negate< T > arithmetic not_equal_to< T > relational plus< T > arithmetic multiplies< T > arithmetic
  • 29.
    class FunctoinObject { public: template<class T> Toperator() (T t) const{…;}; } Demo Function Object (Functor)
  • 30.
    Using STL I class TMyClass;  typedef list<TMyClass> TMyClassList; // 用於存放對象的 list 容器  typedef list<TMyClass*> TMyClassPtrList; // 用於存放 對象指針的 list 容器
  • 31.
    Using STL II classTMyClass { private: ... public: TMyClass(..); // 拷貝構造函數 TMyClass(const TMyClass& obj) { *this = obj; } // 賦值操作符 TMyClass& operator=(const TMyClass& obj); ... };
  • 32.
    Using STL III TMyClassobject; TMyClassList myList; TMyClassList::iterator it; it = myList.insert(myList.end(), object); TMyClass *pObject = &(*it);
  • 33.
    Using STL IIII TMyClassList::iteratorit; TMyClass *pObject; for (it = myList.begin(); it != myList.end(); it ++) { pObject = &(*it); // 使用 pObject } //pObject = *it;
  • 34.
    Using STL V TMyClassList::iteratorit; TMyClass *pObject; for (it = myList.begin(); it != myList.end(); it ++) { pObject = &(*it); if (pObject 滿足某些刪除的標註 ) then myList.erase(it); // 若 list 裡面保存的是指針,那麼增加下面代碼 delete pObject; }
  • 35.
  • 36.
    測試結果 範例: Deitel C++How To Program Ch21 Cl Version 14.00.50727.42 全通過 gcc version 3.4.2 (mingw-special) 十二個 bcc32 九個
  • 37.
    Reference C++ How toProgram 3rd. STL 源碼剖析 STL中文站
  • 38.
  • 39.
  • 40.