Professional Documents
Culture Documents
D05 STL
D05 STL
2003 Prentice Hall, Inc. All rights reserved. 2003 Prentice Hall, Inc. All rights reserved.
2 4
Tổng quan
Thư viện khuôn mẫu chuẩn - STL
• Thư viện chuẩn C++ bao gồm 32 header file, trong
đó ta đã làm quen với một số file (ít nhất đến một • Một số lời khuyên về STL
mức độ nào đó) – STL được thiết kế đẹp và hiệu quả - không có thừa kế
hay hàm ảo trong bất kỳ định nghĩa nào
<algorithm> <ios> <map> <stack>
– Từ tư tưởng lập trình tổng quát dẫn tới những "khối cơ
<bitset> <iosfwd> <memory> <stdexcept>
bản" (building block) mà có thể kết hợp với nhau theo
<complex> <iostream> <new> <streambuf>
đủ kiểu
<deque> <istream> <numeric> <string>
<exception> <iterator> <ostream> <typeinfo> – Tuy làm quen với STL tốn không ít thời gian nhưng
<fstream> <limits> <queue> <utility>
thành quả tiềm tàng về năng xuất rất xứng đáng với thời
<functional> <list> <set> <valarray>
gian đầu tư
<iomanip> <locale> <sstream> <vector> – Tóm lại – hãy học và hãy sử dụng!
• Bài giảng này chỉ để giới thiệu một phần rất nhỏ của
STL
2003 Prentice Hall, Inc. All rights reserved. 2003 Prentice Hall, Inc. All rights reserved.
5 7
• Ba thành phần chính của STL • Các hàm thành viên mọi container đều có
– Các thành phần rất mạnh xây dựng dựa trên – Default constructor, copy constructor, destructor
template – empty
– max_size, size
• Container: các cấu trúc dữ liệu template
– = < <= > >= == !=
• Iterator: giống con trỏ, dùng để truy nhập các phần
– swap
tử dữ liệu của các container
• Algorithm: các thuật toán để thao tác dữ liệu, tìm • Các hàm thành viên của first-class container
kiếm, sắp xếp, v.v.. – begin, end
– rbegin, rend
– erase, clear
2003 Prentice Hall, Inc. All rights reserved. 2003 Prentice Hall, Inc. All rights reserved.
6 8
2003 Prentice Hall, Inc. All rights reserved. 2003 Prentice Hall, Inc. All rights reserved.
9 11
2003 Prentice Hall, Inc. All rights reserved. 2003 Prentice Hall, Inc. All rights reserved.
10 12
Các loại Iteratorđược hỗ trợ Giới thiệu các thuật toán – Algorithm
• Sequence container • STL có các thuật toán được sử dụng tổng quát cho
– vector: random access nhiều loại container
– deque: random access – thao tác gián tiếp với các phần tử qua các iterator
– list: bidirectional – thường dùng cho các phần tử trong một chuỗi
• Associative container • chuỗi xác định bởi một cặp iterator trỏ tới phần tử đầu tiên và
cuối cùng của chuỗi
(hỗ trợ các loại bidirectional) – các thuật toán thường trả về iterator
– set, multiset,map, multimap • ví dụ: find() trả về iterator trỏ tới phần tử cần tìm hoặc trả
• Container adapter (không hỗ trợ iterator) về end() nếu không tìm thấy
– stack, queue, priority_queue – sử dụng các thuật toán được cung cấp giúp lập trình viên tiết
kiệm thời gian và công sức
2003 Prentice Hall, Inc. All rights reserved. 2003 Prentice Hall, Inc. All rights reserved.
13 15
2003 Prentice Hall, Inc. All rights reserved. 2003 Prentice Hall, Inc. All rights reserved.
14 16
2003 Prentice Hall, Inc. All rights reserved. 2003 Prentice Hall, Inc. All rights reserved.
17 19
18 20
27 // function push_back is in every sequence collection
Outline
sử dụng push_back để
21.2.1 vector Sequence Container 28
29
integers.push_back( 2
integers.push_back( 3
);
);
thêm phần tử vào cuối
vector
30 integers.push_back( 4 ); fig21_14.cpp
31 (2 of 3)
• Các hàm thành viên của vector 32 cout << "\nThe size of integers is: " << integers.size()
33 << "\nThe capacity of integers is: "
– v.front(), v.back() 34 << integers.capacity();
35
• Trả về phần tử đầu tiên và cuối cùng 36 cout << "\n\nOutput array using pointer notation: ";
– v.[elementNumber] = value; 37
38 for ( int *ptr = array; ptr != array + SIZE; ++ptr )
• Gán giá trị value cho một phần tử 39 cout << *ptr << ' ';
40
– v.at[elementNumber] = value; 41 cout << "\nOutput vector using iterator notation: ";
• Như trên, nhưng kèm theo kiểm tra chỉ số hợp lệ 42 printVector( integers );
43
• có thể ném ngoại lệ out_of_bounds 44 cout << "\nReversed contents of vector integers: ";
45
22 24
The initial size of v is: 0 26 integers[ 0 ] = 7; // set first element to 7
Outline 27 integers.at( 2 ) = 10; // set element at position 2 to 10
Outline
The initial capacity of v is: 0
28
The size of v is: 3
29 // insert 22 as 2nd element
The capacity of v is: 4 fig21_14.cpp More vector member
fig21_15.cpp
30 integers.insert( integers.begin() + 1, 22 );
output (1 of 1) 31
functions. (2 of 3)
Contents of array a using pointer notation: 1 2 3 4 5 6 32 cout << "\n\nContents of vector integers after changes: " ;
Contents of vector v using iterator notation: 2 3 4 33 std::copy( integers.begin(), integers.end(), output );
Reversed contents of vector v: 4 3 2 34
35 // access out-of-range element at has range checking, and
36 try { can throw an exception.
37 integers.at( 100 ) = 777;
38
39 } // end try
40
41 // catch out_of_range exception
42 catch ( std::out_of_range outOfRange ) {
43 cout << "\n\nException: " << outOfRange.what();
44
45 } // end catch
46
47 // erase first element
48 integers.erase( integers.begin() );
49 cout << "\n\nVector integers after erasing first element: " ;
50 std::copy( integers.begin(), integers.end(), output );
51
Smith Nguyen
Adapter Studio.
52 // erase remaining elements
53 integers.erase( integers.begin(), integers.end() );
Outline
54 cout << "\nAfter erasing all elements, vector integers " Container
55 << ( integers.empty() ? "is" : "is not" ) << " empty";
fig21_15.cpp
56
57 // insert elements from array
(3 of 3)
58 integers.insert( integers.begin(), array, array + SIZE ); • Container adapter
59 cout << "\n\nContents of vector integers before clear: " ;
60 std::copy( integers.begin(), integers.end(), output ); – stack, queue và priority_queue
61
62 // empty integers; clear calls erase to empty a collection
– Không phải first class container, cho nên
63 integers.clear(); • Không hỗ trợ iterator
64 cout << "\nAfter clear, vector integers "
65 << ( integers.empty() ? "is" : "is not" ) << " empty"; • Không cung cấp cấu trúc dữ liệu
66
67 cout << endl; – Lập trình viên có thể chọn cách cài đặt (sử dụng cấu trúc dữ
68 liệu nào)
69 return 0;
70 – đều cung cấp các hàm thành viên push và pop bên cạch
71 } // end main
các hàm thành viên khác.
26 28
Vector integers contains: 1 2 3 4 5 6
First element of integers: 1
Outline
Last element of integers: 6 stack Adapter
fig21_15.cpp
Contents of vector integers after changes: 7 22 2 10 4 5 6
output (1 of 1)
Exception: invalid vector<T> subscript • stack
Vector integers after erasing first element: 22 2 10 4 5 6 – Header <stack>
After erasing all elements, vector integers is empty
– chèn và xóa tại một đầu
Contents of vector integers before clear: 1 2 3 4 5 6
After clear, vector integers is empty
– Cấu trúc Last-in, first-out (LIFO)
– Có thể chọn cài đặt bằng vector, list, hoặc deque
(mặc định)
– Khai báo
stack<type, vector<type> > myStack;
stack<type, list<type> > myOtherStack;
stack<type> anotherStack; // default deque
– chọn cài đặt là vector, list hay deque không làm
thay đổi hành vi, chỉ ảnh hưởng tới hiệu quả (cài bằng
deque và vector là nhanh nhất)
2003 Prentice Hall, Inc.
All rights reserved. 2003 Prentice Hall, Inc. All rights reserved.
29 31
30 32
27 // push the values 0-9 onto each stack
Outline
28
29
for ( int i = 0; i < 10; ++i ) {
intDequeStack.push( i );
Các thuật toán
30 intVectorStack.push( i ); viên push.
sử dụng hàm thành fig21_23.cpp
31 intListStack.push( i ); (2 of 3)
32 • Trước STL
33 } // end for
34 – các thư viện của các hãng khác nhau không tương
35 // display and remove elements from each stack
36 cout << "Popping from intDequeStack: ";
thích
37
38
popElements( intDequeStack );
cout << "\nPopping from intVectorStack: ";
– Các thuật toán được xây dựng và gắn vào trong các
39 popElements( intVectorStack ); lớp container
40 cout << "\nPopping from intListStack: ";
41
42
popElements( intListStack ); • STL tách rời các container và các thuật toán
43 cout << endl; – lợi thế:
44
45 return 0; • dễ bổ sung các thuật toán mới
46
47 } // end main
• hiệu quả hơn, tránh các lời gọi hàm ảo
48
– header <algorithm>
Smith
Các thuậtNguyen
toán toán họcStudio.
remove, remove_if, remove_copy và
remove_copy_if
• remove • random_shuffle(iter1, iter2)
– remove( iter1, iter2, value); – xáo trộn các phần tử trong khoảng một cách ngẫu nhiên
– Bỏ mọi phần tử có giá trị value trong khoảng (iter1- • count(iter1, iter2, value)
iter2) theo cách sau: – trả về số lần xuất hiện của value trong khoảng
• Chuyển các phần tử có giá trị value xuống cuối • count_if(iter1, iter2, function)
• không thay đổi kích thước của container hoặc thực sự xóa các – đếm số phần tử làm function trả về true
phần tử • min_element(iter1, iter2)
– Trả về iterator tới kết thúc “mới” của container – trả về iterator tới phần tử nhỏ nhất
– các phần tử sau kết thúc mới là không xác định • max_element(iter1, iter2)
• remove_copy – trả về iterator tới phần tử lớn nhất
– remove_copy(iter1, iter2, iter3, value);
• trong khoảng iter1-iter2, chép các phần tử khác
value vào iter3 (output iterator)
2003 Prentice Hall, Inc. All rights reserved. 2003 Prentice Hall, Inc. All rights reserved.
34 36
remove, remove_if, remove_copy và
Các thuật toán toán học
remove_copy_if
• remove_if • accumulate(iter1, iter2)
– giống remove – trả về tổng các phần tử trong khoảng
• trả về iterator tới phần tử cuối cùng • for_each(iter1, iter2, function)
• bỏ các phần tử mà hàm trả về true – Gọi hàm function cho mỗi phần tử trong khoảng
remove_if(iter1,iter2, function); – không sửa đổi phần tử
• các phần tử được truyền cho function, hàm này trả về giá • transform(iter1, iter2, iter3, function)
trị bool – gọi function cho mọi phần tử trong khoảng iter1-iter2,
kết quả ghi vào iter3
• remove_copy_if
– giống remove_copy và remove_if
remove_copy_if(iter1, iter2, iter3, function);
2003 Prentice Hall, Inc. All rights reserved. 2003 Prentice Hall, Inc. All rights reserved.
37 39
38 40
1 // Fig. 21.31: fig21_31.cpp 53 // sort elements of v
Outline Outline
2 // Standard library search and sort algorithms. 54 std::sort( v.begin(), v.end() );
3 #include <iostream> 55
4 fig21_31.cpp 56 cout << "\n\nVector v after sort: "; fig21_31.cpp
5 using std::cout; (1 of 4) 57 std::copy( v.begin(), v.end(), output ); (3 of 4)
6 using std::endl; 58
7 59 // use binary_search to locate 13 in v
8 #include <algorithm> // algorithm definitions 60 if ( std::binary_search( v.begin(), v.end(), 13 ) )
9 #include <vector> // vector class-template definition 61 cout << "\n\n13 was found in v";
10 62 else
11 bool greater10( int value ); // prototype 63 cout << "\n\n13 was not found in v";
12 64
13 int main() 65 // use binary_search to locate 100 in v
14 { 66 if ( std::binary_search( v.begin(), v.end(), 100 ) )
15 const int SIZE = 10; 67 cout << "\n100 was found in v";
16 int a[ SIZE ] = { 10, 2, 17, 5, 16, 8, 13, 11, 20, 7 }; 68 else
17 69 cout << "\n100 was not found in v";
18 std::vector< int > v( a, a + SIZE ); 70
19 std::ostream_iterator< int > output( cout, " " ); 71 cout << endl;
20 72
21 cout << "Vector v contains: "; 73 return 0;
22 std::copy( v.begin(), v.end(), output ); 74
23 75 } // end main
24 // locate first occurrence of 16 in v 76
25 std::vector< int >::iterator location; 2003 Prentice Hall, Inc. 2003 Prentice Hall, Inc.
26 location = std::find( v.begin(), v.end(), 16 ); All rights reserved. All rights reserved.
41 43
42 44
21 // binary function class template defines overloaded operator()
Outline
Function Object – functor 22
23
// that adds suare of its second argument and running total in
// its first argument, then returns sum
24 template< class T >
STL function objects Type 25 class SumSquaresClass : public std::binary_function< T, T, T > {fig21_42.cpp
• Function object divides< T > arithmetic 26 (2 of 4)
27 public:
(<functional>) equal_to< T > relational
28
Tạo một function object (nó
còn có thể đóng gói dữ liệu).
greater< T > relational
– Các đối tượng có thể gọi 29 // add square of value to total and return result Overload operator().
greater_equal< T > relational 30 const T operator()( const T &total, const T &value )
như hàm bằng toán tử () 31 {
less< T > relational
32 return total + value * value;
less_equal< T > relational
33
logical_and< T > logical 34 } // end function operator()
logical_not< T > logical 35
logical_or< T > logical 36 }; // end class SumSquaresClass
minus< T > 37
arithmetic
modulus< T > arithmetic
negate< T > arithmetic
not_equal_to< T > relational
plus< T > arithmetic
multiplies< T > arithmetic
46
60 // calculate sum of squares of elements of vector integers
Outline
61 // using binary-function object
62 result = std::accumulate( integers.begin(), integers.end(),
63 0, SumSquaresClass< int >() ); fig21_42.cpp
64 (4 of 4)
65 cout << "\n\nSum of squares of elements in integers using "
66 << "binary\nfunction object of type " fig21_42.cpp
67 << "SumSquaresClass< int >: " << result << endl; output (1 of 1)
68 dùng accumulate với một
69 return 0; function object.
70
71 } // end main
vector v contains:
1 2 3 4 5 6 7 8 9 10