SlideShare a Scribd company logo
1 of 12
Download to read offline
© 2003 Prentice Hall, Inc. All rights reserved.
1
Thư viện chuẩn C++
Standard Template Library (STL)
© 2003 Prentice Hall, Inc. All rights reserved.
2
Tổng quan
• 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ức độ nào đó)
<algorithm>
<bitset>
<complex>
<deque>
<exception>
<fstream>
<functional>
<iomanip>
<ios>
<iosfwd>
<iostream>
<istream>
<iterator>
<limits>
<list>
<locale>
<stack>
<stdexcept>
<streambuf>
<string>
<typeinfo>
<utility>
<valarray>
<vector>
<map>
<memory>
<new>
<numeric>
<ostream>
<queue>
<set>
<sstream>
© 2003 Prentice Hall, Inc. All rights reserved.
3
Thư viện khuôn mẫu chuẩn - STL
• Thư viện chuẩn C++ gồm 2 phần:
– Lớp string
– Thư viện khuôn mẫu chuẩn – STL
• Ngoại trừ lớp string, tất cả các thành phần còn lại của thư viện
đều là các khuôn mẫu
• Tác giả đầu tiên của STL là Alexander Stepanov, mục đích của
ông là xây dựng một cách thể hiện tư tưởng lập trình tổng quát
• Các khái niệm trong STL được phát triển độc lập với C++
– Do đó, ban đầu, STL không phải là một thư viện C++, mà nó đã được
chuyển đổi thành thư viện C++
– Nhiều tư tưởng dẫn đến sự phát triển của STL đã được cài đặt phần nào
trong Scheme, Ada, và C
© 2003 Prentice Hall, Inc. All rights reserved.
4
Thư viện khuôn mẫu chuẩn - STL
• Một số lời khuyên về STL
– 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
– Từ tư tưởng lập trình tổng quát dẫn tới những "khối cơ
bản" (building block) mà có thể kết hợp với nhau theo
đủ kiểu
– Tuy làm quen với STL tốn không ít thời gian nhưng
thành quả tiềm tàng về năng xuất rất xứng đáng với thời
gian đầu tư
– 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.
5
Giới thiệu Standard Template Library (STL)
• Ba thành phần chính của STL
– Các thành phần rất mạnh xây dựng dựa trên
template
• 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
tử dữ liệu của các container
• Algorithm: các thuật toán để thao tác dữ liệu, tìm
kiếm, sắp xếp, v.v..
© 2003 Prentice Hall, Inc. All rights reserved.
6
Giới thiệu về các Container
• 3 loại container
– Sequence container – container chuỗi
• các cấu trúc dữ liệu tuyến tính (vector, danh sách liên kết)
• first-class container
• vector, deque, list
– Associative container – container liên kết
• các cấu trúc phi tuyến, có thể tìm phần tử nhanh chóng
• first-class container
• các cặp khóa/giá trị
• set, multiset, map, multimap
– Container adapter – các bộ tương thích container
• stack, queue, priority_queue
© 2003 Prentice Hall, Inc. All rights reserved.
7
Các hàm thành viên STL
• Các hàm thành viên mọi container đều có
– Default constructor, copy constructor, destructor
– empty
– max_size, size
– = < <= > >= == !=
– swap
• Các hàm thành viên của first-class container
– begin, end
– rbegin, rend
– erase, clear
© 2003 Prentice Hall, Inc. All rights reserved.
8
Giới thiệu về Iterator
• Iterator tương tự như con trỏ
– trỏ tới các phần tử trong một container
– các toán tử iterator cho mọi container
• * truy nhập phần tử được trỏ tới
• ++ trỏ tới phần tử tiếp theo
• begin() trả về iterator trỏ tới phần tử đầu tiên
• end() trả về iterator trỏ tới phần tử đặc biệt chặn cuối
container
© 2003 Prentice Hall, Inc. All rights reserved.
9
Các loại Iterator
• Input (ví dụ: istream_iterator)
– Đọc các phần tử từ một container, hỗ trợ ++,+= (chỉ tiến)
• Output (ví dụ: ostream_iterator)
– Ghi các phần tử vào container, hỗ trợ ++,+= (chỉ tiến)
• Forward (ví dụ: hash_set<T> iterator)
– Kết hợp input iterator và output iterator
– Multi-pass (có thể duyệt chuỗi nhiều lần)
• Bidirectional (Ví dụ: list<T> iterator)
– Như forward iterator, nhưng có thể lùi (--,-=)
• Random access (Ví dụ: vector<T> iterator)
– Như bidirectional, nhưng còn có thể nhảy tới phần tử tùy ý
© 2003 Prentice Hall, Inc. All rights reserved.
10
Các loại Iteratorđược hỗ trợ
• Sequence container
– vector: random access
– deque: random access
– list: bidirectional
• Associative container
(hỗ trợ các loại bidirectional)
– set, multiset,map, multimap
• Container adapter (không hỗ trợ iterator)
– stack, queue, priority_queue
© 2003 Prentice Hall, Inc. All rights reserved.
11
Các phép toán đối với Iterator
• Input iterator
++ , =*p , -> , == , !=
• Output iterator
++ , *p= , p = p1
• Forward iterator
– Kết hợp các toán tử của input và output iterator
• Bidirectional iterator
các toán tử cho forward, và
--
• Random iterator
các toán tử cho bidirectional, và
+ , +=, -, -=, >, >=, <, <=,[]
© 2003 Prentice Hall, Inc. All rights reserved.
12
Giới thiệu các thuật toán – Algorithm
• STL có các thuật toán được sử dụng tổng quát cho
nhiều loại container
– thao tác gián tiếp với các phần tử qua các iterator
– thường dùng cho các phần tử trong một chuỗi
• 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
– các thuật toán thường trả về iterator
• ví dụ: find() trả về iterator trỏ tới phần tử cần tìm hoặc trả
về end() nếu không tìm thấy
– 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.
13
Sequence Container
• 3 loại sequence container:
– vector – dựa theo mảng
– deque – dựa theo mảng
– list – danh sách liên kết hiệu quả cao
© 2003 Prentice Hall, Inc. All rights reserved.
14
vector Sequence Container
• vector
– <vector>
– cấu trúc dữ liệu với các vùng nhớ liên tiếp
• truy nhập các phần tử bằng toán tử []
– sử dụng khi dữ liệu cần được sắp xếp và truy nhập dễ dàng
• Cơ chế hoạt động khi hết bộ nhớ
– cấp phát một vùng nhớ liên lục lớn hơn
– tự sao chép ra vùng nhớ mới
– trả lại vùng nhớ cũ
• sử dụng random access iterator
© 2003 Prentice Hall, Inc. All rights reserved.
15
vector Sequence Container
• Khai báo
– std::vector <type> v;
• type là kiểu dữ liệu của phần tử dữ liệu (int, float, v.v..)
• Iterator
– std::vector<type>::iterator iterVar;
• trường hợp thông thường
– std::vector<type>::const_iterator iterVar;
• const_iterator không thể sửa đổi các phần tử
– std::vector<type>::reverse_iterator iterVar;
• Visits elements in reverse order (end to beginning)
• Use rbegin to get starting point
• Use rend to get ending point
© 2003 Prentice Hall, Inc. All rights reserved.
16
vector Sequence Container
• Các hàm thành viên của vector
– v.push_back(value)
• thêm phần tử vào cuối (sequence container nào cũng có hàm
này).
– v.size()
• kích thước hiện tại của vector
– v.capacity()
• kích thước có thể lưu trữ trước khi phải cấp phát lại
• khi cấp phát lại sẽ cấp phát kích thước gấp đôi
– vector<type> v(a, a + SIZE)
• tạo vector v từ SIZE phần tử đầu tiên của mảng a
© 2003 Prentice Hall, Inc. All rights reserved.
17
vector Sequence Container
• Các hàm thành viên của vector
– v.insert(iterator, value )
• chèn value vào trước vị trí của iterator
– v.insert(iterator, array , array + SIZE)
• chèn vào vector SIZE phần tử đầu tiên của mảng array
– v.erase( iterator )
• xóa phần tử khỏi container
– v.erase( iter1, iter2 )
• xóa bỏ các phần tử bắt đầu từ iter1 đến hết phần tử liền
trước iter2
– v.clear()
• Xóa toàn bộ container
© 2003 Prentice Hall, Inc. All rights reserved.
18
21.2.1 vector Sequence Container
• Các hàm thành viên của vector
– v.front(), v.back()
• Trả về phần tử đầu tiên và cuối cùng
– v.[elementNumber] = value;
• Gán giá trị value cho một phần tử
– v.at[elementNumber] = value;
• Như trên, nhưng kèm theo kiểm tra chỉ số hợp lệ
• có thể ném ngoại lệ out_of_bounds
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
19
fig21_14.cpp
(1 of 3)
1 // Fig. 21.14: fig21_14.cpp
2 // Demonstrating standard library vector class template.
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 #include <vector> // vector class-template definition
10
11 // prototype for function template printVector
12 template < class T >
13 void printVector( const std::vector< T > &integers2 );
14
15 int main()
16 {
17 const int SIZE = 6;
18 int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 };
19
20 std::vector< int > integers;
21
22 cout << "The initial size of integers is: "
23 << integers.size()
24 << "nThe initial capacity of integers is: "
25 << integers.capacity();
26
Tạo một vector chứa các giá trị int
Gọi các hàm thành viên.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
20
fig21_14.cpp
(2 of 3)
27 // function push_back is in every sequence collection
28 integers.push_back( 2 );
29 integers.push_back( 3 );
30 integers.push_back( 4 );
31
32 cout << "nThe size of integers is: " << integers.size()
33 << "nThe capacity of integers is: "
34 << integers.capacity();
35
36 cout << "nnOutput array using pointer notation: ";
37
38 for ( int *ptr = array; ptr != array + SIZE; ++ptr )
39 cout << *ptr << ' ';
40
41 cout << "nOutput vector using iterator notation: ";
42 printVector( integers );
43
44 cout << "nReversed contents of vector integers: ";
45
sử dụng push_back để
thêm phần tử vào cuối
vector
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
21
fig21_14.cpp
(3 of 3)
46 std::vector< int >::reverse_iterator reverseIterator;
47
48 for ( reverseIterator = integers.rbegin();
49 reverseIterator!= integers.rend();
50 ++reverseIterator )
51 cout << *reverseIterator << ' ';
52
53 cout << endl;
54
55 return 0;
56
57 } // end main
58
59 // function template for outputting vector elements
60 template < class T >
61 void printVector( const std::vector< T > &integers2 )
62 {
63 std::vector< T >::const_iterator constIterator;
64
65 for ( constIterator = integers2.begin();
66 constIterator != integers2.end();
67 constIterator++ )
68 cout << *constIterator << ' ';
69
70 } // end function printVector
Duyệt ngược vector bằng
một reverse_iterator.
Template function để duyệt
vector theo chiều tiến.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
22
fig21_14.cpp
output (1 of 1)
The initial size of v is: 0
The initial capacity of v is: 0
The size of v is: 3
The capacity of v is: 4
Contents of array a using pointer notation: 1 2 3 4 5 6
Contents of vector v using iterator notation: 2 3 4
Reversed contents of vector v: 4 3 2
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
23
fig21_15.cpp
(1 of 3)
1 // Fig. 21.15: fig21_15.cpp
2 // Testing Standard Library vector class template
3 // element-manipulation functions.
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 #include <vector> // vector class-template definition
10 #include <algorithm> // copy algorithm
11
12 int main()
13 {
14 const int SIZE = 6;
15 int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 };
16
17 std::vector< int > integers( array, array + SIZE );
18 std::ostream_iterator< int > output( cout, " " );
19
20 cout << "Vector integers contains: ";
21 std::copy( integers.begin(), integers.end(), output );
22
23 cout << "nFirst element of integers: " << integers.front()
24 << "nLast element of integers: " << integers.back();
25
Create vector (initialized
using an array) and
ostream_iterator.
Copy range of iterators to output
(ostream_iterator).
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
24
fig21_15.cpp
(2 of 3)
26 integers[ 0 ] = 7; // set first element to 7
27 integers.at( 2 ) = 10; // set element at position 2 to 10
28
29 // insert 22 as 2nd element
30 integers.insert( integers.begin() + 1, 22 );
31
32 cout << "nnContents of vector integers after changes: " ;
33 std::copy( integers.begin(), integers.end(), output );
34
35 // access out-of-range element
36 try {
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 << "nnException: " << outOfRange.what();
44
45 } // end catch
46
47 // erase first element
48 integers.erase( integers.begin() );
49 cout << "nnVector integers after erasing first element: " ;
50 std::copy( integers.begin(), integers.end(), output );
51
More vector member
functions.
at has range checking, and
can throw an exception.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
25
fig21_15.cpp
(3 of 3)
52 // erase remaining elements
53 integers.erase( integers.begin(), integers.end() );
54 cout << "nAfter erasing all elements, vector integers "
55 << ( integers.empty() ? "is" : "is not" ) << " empty";
56
57 // insert elements from array
58 integers.insert( integers.begin(), array, array + SIZE );
59 cout << "nnContents of vector integers before clear: ";
60 std::copy( integers.begin(), integers.end(), output );
61
62 // empty integers; clear calls erase to empty a collection
63 integers.clear();
64 cout << "nAfter clear, vector integers "
65 << ( integers.empty() ? "is" : "is not" ) << " empty";
66
67 cout << endl;
68
69 return 0;
70
71 } // end main
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
26
fig21_15.cpp
output (1 of 1)
Vector integers contains: 1 2 3 4 5 6
First element of integers: 1
Last element of integers: 6
Contents of vector integers after changes: 7 22 2 10 4 5 6
Exception: invalid vector<T> subscript
Vector integers after erasing first element: 22 2 10 4 5 6
After erasing all elements, vector integers is empty
Contents of vector integers before clear: 1 2 3 4 5 6
After clear, vector integers is empty
© 2003 Prentice Hall, Inc. All rights reserved.
27
Container Adapter
• Container adapter
– stack, queue và priority_queue
– Không phải first class container, cho nên
• Không hỗ trợ iterator
• Không cung cấp cấu trúc dữ liệu
– Lập trình viên có thể chọn cách cài đặt (sử dụng cấu trúc dữ
liệu nào)
– đều cung cấp các hàm thành viên push và pop bên cạch
các hàm thành viên khác.
© 2003 Prentice Hall, Inc. All rights reserved.
28
stack Adapter
• stack
– Header <stack>
– chèn và xóa tại một đầu
– 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.
Outline
29
fig21_23.cpp
(1 of 3)
1 // Fig. 21.23: fig21_23.cpp
2 // Standard library adapter stack test program.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <stack> // stack adapter definition
9 #include <vector> // vector class-template definition
10 #include <list> // list class-template definition
11
12 // popElements function-template prototype
13 template< class T >
14 void popElements( T &stackRef );
15
16 int main()
17 {
18 // stack with default underlying deque
19 std::stack< int > intDequeStack;
20
21 // stack with underlying vector
22 std::stack< int, std::vector< int > > intVectorStack;
23
24 // stack with underlying list
25 std::stack< int, std::list< int > > intListStack;
26
Tạo stack bằng nhiều kiểu cài đặt.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
30
fig21_23.cpp
(2 of 3)
27 // push the values 0-9 onto each stack
28 for ( int i = 0; i < 10; ++i ) {
29 intDequeStack.push( i );
30 intVectorStack.push( i );
31 intListStack.push( i );
32
33 } // end for
34
35 // display and remove elements from each stack
36 cout << "Popping from intDequeStack: ";
37 popElements( intDequeStack );
38 cout << "nPopping from intVectorStack: ";
39 popElements( intVectorStack );
40 cout << "nPopping from intListStack: ";
41 popElements( intListStack );
42
43 cout << endl;
44
45 return 0;
46
47 } // end main
48
sử dụng hàm thành viên push.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
31
fig21_23.cpp
(3 of 3)
fig21_23.cpp
output (1 of 1)
49 // pop elements from stack object to which stackRef refers
50 template< class T >
51 void popElements( T &stackRef )
52 {
53 while ( !stackRef.empty() ) {
54 cout << stackRef.top() << ' '; // view top element
55 stackRef.pop(); // remove top element
56
57 } // end while
58
59 } // end function popElements
Popping from intDequeStack: 9 8 7 6 5 4 3 2 1 0
Popping from intVectorStack: 9 8 7 6 5 4 3 2 1 0
Popping from intListStack: 9 8 7 6 5 4 3 2 1 0
© 2003 Prentice Hall, Inc. All rights reserved.
32
Các thuật toán
• Trước STL
– các thư viện của các hãng khác nhau không tương
thích
– Các thuật toán được xây dựng và gắn vào trong các
lớp container
• STL tách rời các container và các thuật toán
– lợi thế:
• dễ bổ sung các thuật toán mới
• hiệu quả hơn, tránh các lời gọi hàm ảo
– header <algorithm>
© 2003 Prentice Hall, Inc. All rights reserved.
33
remove, remove_if, remove_copy và
remove_copy_if
• remove
– remove( iter1, iter2, value);
– Bỏ mọi phần tử có giá trị value trong khoảng (iter1-
iter2) theo cách sau:
• Chuyển các phần tử có giá trị value xuống cuối
• không thay đổi kích thước của container hoặc thực sự xóa các
phần tử
– Trả về iterator tới kết thúc “mới” của container
– các phần tử sau kết thúc mới là không xác định
• remove_copy
– 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.
34
remove, remove_if, remove_copy và
remove_copy_if
• remove_if
– giống remove
• trả về iterator tới phần tử cuối cùng
• bỏ các phần tử mà hàm trả về true
remove_if(iter1,iter2, function);
• các phần tử được truyền cho function, hàm này trả về giá
trị bool
• remove_copy_if
– giống remove_copy và remove_if
remove_copy_if(iter1, iter2, iter3, function);
© 2003 Prentice Hall, Inc. All rights reserved.
35
Các thuật toán toán học
• random_shuffle(iter1, iter2)
– xáo trộn các phần tử trong khoảng một cách ngẫu nhiên
• count(iter1, iter2, value)
– trả về số lần xuất hiện của value trong khoảng
• count_if(iter1, iter2, function)
– đếm số phần tử làm function trả về true
• min_element(iter1, iter2)
– trả về iterator tới phần tử nhỏ nhất
• max_element(iter1, iter2)
– trả về iterator tới phần tử lớn nhất
© 2003 Prentice Hall, Inc. All rights reserved.
36
Các thuật toán toán học
• accumulate(iter1, iter2)
– trả về tổng các phần tử trong khoảng
• for_each(iter1, iter2, function)
– Gọi hàm function cho mỗi phần tử trong khoảng
– không sửa đổi phần tử
• transform(iter1, iter2, iter3, function)
– gọi function cho mọi phần tử trong khoảng iter1-iter2,
kết quả ghi vào iter3
© 2003 Prentice Hall, Inc. All rights reserved.
37
Các thuật toán tìm kiếm và sắp xếp cơ bản
• find(iter1, iter2, value)
– trả về iterator tới lần xuất hiện đầu tiên (trong khoảng) của
value
• find_if(iter1, iter2, function)
– như find
– trả về iterator khi function trả về true
• sort(iter1, iter2)
– sắp xếp các phần tử theo thứ tự tăng dần
• binary_search(iter1, iter2, value)
– tìmgiá trị trong dãy sắp xếp tăng dần,
– sử dụng thuật toán tìm kiếm nhị phân
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
38
fig21_31.cpp
(1 of 4)
1 // Fig. 21.31: fig21_31.cpp
2 // Standard library search and sort algorithms.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <algorithm> // algorithm definitions
9 #include <vector> // vector class-template definition
10
11 bool greater10( int value ); // prototype
12
13 int main()
14 {
15 const int SIZE = 10;
16 int a[ SIZE ] = { 10, 2, 17, 5, 16, 8, 13, 11, 20, 7 };
17
18 std::vector< int > v( a, a + SIZE );
19 std::ostream_iterator< int > output( cout, " " );
20
21 cout << "Vector v contains: ";
22 std::copy( v.begin(), v.end(), output );
23
24 // locate first occurrence of 16 in v
25 std::vector< int >::iterator location;
26 location = std::find( v.begin(), v.end(), 16 );
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
39
fig21_31.cpp
(2 of 4)
27
28 if ( location != v.end() )
29 cout << "nnFound 16 at location "
30 << ( location - v.begin() );
31 else
32 cout << "nn16 not found";
33
34 // locate first occurrence of 100 in v
35 location = std::find( v.begin(), v.end(), 100 );
36
37 if ( location != v.end() )
38 cout << "nFound 100 at location "
39 << ( location - v.begin() );
40 else
41 cout << "n100 not found";
42
43 // locate first occurrence of value greater than 10 in v
44 location = std::find_if( v.begin(), v.end(), greater10 );
45
46 if ( location != v.end() )
47 cout << "nnThe first value greater than 10 is "
48 << *location << "nfound at location "
49 << ( location - v.begin() );
50 else
51 cout << "nnNo values greater than 10 were found";
52
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
40
fig21_31.cpp
(3 of 4)
53 // sort elements of v
54 std::sort( v.begin(), v.end() );
55
56 cout << "nnVector v after sort: ";
57 std::copy( v.begin(), v.end(), output );
58
59 // use binary_search to locate 13 in v
60 if ( std::binary_search( v.begin(), v.end(), 13 ) )
61 cout << "nn13 was found in v";
62 else
63 cout << "nn13 was not found in v";
64
65 // use binary_search to locate 100 in v
66 if ( std::binary_search( v.begin(), v.end(), 100 ) )
67 cout << "n100 was found in v";
68 else
69 cout << "n100 was not found in v";
70
71 cout << endl;
72
73 return 0;
74
75 } // end main
76
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
41
fig21_31.cpp
(4 of 4)
fig21_31.cpp
output (1 of 1)
77 // determine whether argument is greater than 10
78 bool greater10( int value )
79 {
80 return value > 10;
81
82 } // end function greater10
Vector v contains: 10 2 17 5 16 8 13 11 20 7
Found 16 at location 4
100 not found
The first value greater than 10 is 17
found at location 2
Vector v after sort: 2 5 7 8 10 11 13 16 17 20
13 was found in v
100 was not found in v
© 2003 Prentice Hall, Inc. All rights reserved.
42
Function Object – functor
• Function object
(<functional>)
– Các đối tượng có thể gọi
như hàm bằng toán tử ()
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
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
43
fig21_42.cpp
(1 of 4)
1 // Fig. 21.42: fig21_42.cpp
2 // Demonstrating function objects.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <vector> // vector class-template definition
9 #include <algorithm> // copy algorithm
10 #include <numeric> // accumulate algorithm
11 #include <functional> // binary_function definition
12
13 // binary function adds square of its second argument and
14 // running total in its first argument, then returns sum
15 int sumSquares( int total, int value )
16 {
17 return total + value * value;
18
19 } // end function sumSquares
20
Tạo một hàm để dùng với
accumulate.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
44
fig21_42.cpp
(2 of 4)
21 // binary function class template defines overloaded operator()
22 // that adds suare of its second argument and running total in
23 // its first argument, then returns sum
24 template< class T >
25 class SumSquaresClass : public std::binary_function< T, T, T > {
26
27 public:
28
29 // add square of value to total and return result
30 const T operator()( const T &total, const T &value )
31 {
32 return total + value * value;
33
34 } // end function operator()
35
36 }; // end class SumSquaresClass
37
Tạo một function object (nó
còn có thể đóng gói dữ liệu).
Overload operator().
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
45
fig21_42.cpp
(3 of 4)
38 int main()
39 {
40 const int SIZE = 10;
41 int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
42
43 std::vector< int > integers( array, array + SIZE );
44
45 std::ostream_iterator< int > output( cout, " " );
46
47 int result = 0;
48
49 cout << "vector v contains:n";
50 std::copy( integers.begin(), integers.end(), output );
51
52 // calculate sum of squares of elements of vector integers
53 // using binary function sumSquares
54 result = std::accumulate( integers.begin(), integers.end(),
55 0, sumSquares );
56
57 cout << "nnSum of squares of elements in integers using "
58 << "binarynfunction sumSquares: " << result;
59
đầu tiên, accumulate
truyền 0 và phần tử thứ nhất
lần lượt làm các tham số. Sau
đó, nó dùng kếtquả trả về làm
tham số thứ nhất, và lặp qua
các phần tử còn lại.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
46
fig21_42.cpp
(4 of 4)
fig21_42.cpp
output (1 of 1)
60 // calculate sum of squares of elements of vector integers
61 // using binary-function object
62 result = std::accumulate( integers.begin(), integers.end(),
63 0, SumSquaresClass< int >() );
64
65 cout << "nnSum of squares of elements in integers using "
66 << "binarynfunction object of type "
67 << "SumSquaresClass< int >: " << result << endl;
68
69 return 0;
70
71 } // end main
vector v contains:
1 2 3 4 5 6 7 8 9 10
Sum of squares of elements in integers using binary
function sumSquares: 385
Sum of squares of elements in integers using binary
function object of type SumSquaresClass< int >: 385
dùng accumulate với một
function object.

More Related Content

What's hot

Core java 9
Core java 9Core java 9
Core java 9. .
 
Python Beginner Class day-04-05-06-iterations
Python Beginner Class day-04-05-06-iterationsPython Beginner Class day-04-05-06-iterations
Python Beginner Class day-04-05-06-iterationsKhánh Nguyễn
 
Core java 8
Core java 8Core java 8
Core java 8. .
 
Python Beginner Class day-02-strings
Python Beginner Class day-02-stringsPython Beginner Class day-02-strings
Python Beginner Class day-02-stringsKhánh Nguyễn
 
Oop unit 12 đồ họa và xử lý sự kiện
Oop unit 12 đồ họa và xử lý sự kiệnOop unit 12 đồ họa và xử lý sự kiện
Oop unit 12 đồ họa và xử lý sự kiệnTráng Hà Viết
 
Python Beginner Class day-11-12-13-database
Python Beginner Class day-11-12-13-databasePython Beginner Class day-11-12-13-database
Python Beginner Class day-11-12-13-databaseKhánh Nguyễn
 
Python Beginner Class day-10-class
Python Beginner Class day-10-classPython Beginner Class day-10-class
Python Beginner Class day-10-classKhánh Nguyễn
 
Python Beginner Class day-03-flow
Python Beginner Class day-03-flowPython Beginner Class day-03-flow
Python Beginner Class day-03-flowKhánh Nguyễn
 
Python Beginner Class day-09-fileio
Python Beginner Class day-09-fileioPython Beginner Class day-09-fileio
Python Beginner Class day-09-fileioKhánh Nguyễn
 
Bài 4: ARRAY VÀ ARRAYLIST - Giáo trình FPT
Bài 4: ARRAY VÀ ARRAYLIST - Giáo trình FPTBài 4: ARRAY VÀ ARRAYLIST - Giáo trình FPT
Bài 4: ARRAY VÀ ARRAYLIST - Giáo trình FPTMasterCode.vn
 
Oop unit 09 lập trình tổng quát
Oop unit 09 lập trình tổng quátOop unit 09 lập trình tổng quát
Oop unit 09 lập trình tổng quátTráng Hà Viết
 
Bai09 ngoai levaxulyngoaile
Bai09 ngoai levaxulyngoaileBai09 ngoai levaxulyngoaile
Bai09 ngoai levaxulyngoaileNhuận Lê Văn
 
Python Beginner Class day-07-08-module
Python Beginner Class day-07-08-modulePython Beginner Class day-07-08-module
Python Beginner Class day-07-08-moduleKhánh Nguyễn
 

What's hot (18)

Oop unit 02 java cơ bản
Oop unit 02 java cơ bảnOop unit 02 java cơ bản
Oop unit 02 java cơ bản
 
Core java 9
Core java 9Core java 9
Core java 9
 
Python Beginner Class day-04-05-06-iterations
Python Beginner Class day-04-05-06-iterationsPython Beginner Class day-04-05-06-iterations
Python Beginner Class day-04-05-06-iterations
 
Core java 8
Core java 8Core java 8
Core java 8
 
Python Beginner Class day-02-strings
Python Beginner Class day-02-stringsPython Beginner Class day-02-strings
Python Beginner Class day-02-strings
 
Oop unit 12 đồ họa và xử lý sự kiện
Oop unit 12 đồ họa và xử lý sự kiệnOop unit 12 đồ họa và xử lý sự kiện
Oop unit 12 đồ họa và xử lý sự kiện
 
Python Beginner Class day-11-12-13-database
Python Beginner Class day-11-12-13-databasePython Beginner Class day-11-12-13-database
Python Beginner Class day-11-12-13-database
 
Python Beginner Class day-10-class
Python Beginner Class day-10-classPython Beginner Class day-10-class
Python Beginner Class day-10-class
 
C6 stack queue
C6 stack queueC6 stack queue
C6 stack queue
 
Oop unit 10 ngoại lệ
Oop unit 10 ngoại lệOop unit 10 ngoại lệ
Oop unit 10 ngoại lệ
 
Python Beginner Class day-03-flow
Python Beginner Class day-03-flowPython Beginner Class day-03-flow
Python Beginner Class day-03-flow
 
Python Beginner Class day-09-fileio
Python Beginner Class day-09-fileioPython Beginner Class day-09-fileio
Python Beginner Class day-09-fileio
 
IO trong Java
IO trong JavaIO trong Java
IO trong Java
 
Bài 4: ARRAY VÀ ARRAYLIST - Giáo trình FPT
Bài 4: ARRAY VÀ ARRAYLIST - Giáo trình FPTBài 4: ARRAY VÀ ARRAYLIST - Giáo trình FPT
Bài 4: ARRAY VÀ ARRAYLIST - Giáo trình FPT
 
Tổng hợp nè
Tổng hợp nèTổng hợp nè
Tổng hợp nè
 
Oop unit 09 lập trình tổng quát
Oop unit 09 lập trình tổng quátOop unit 09 lập trình tổng quát
Oop unit 09 lập trình tổng quát
 
Bai09 ngoai levaxulyngoaile
Bai09 ngoai levaxulyngoaileBai09 ngoai levaxulyngoaile
Bai09 ngoai levaxulyngoaile
 
Python Beginner Class day-07-08-module
Python Beginner Class day-07-08-modulePython Beginner Class day-07-08-module
Python Beginner Class day-07-08-module
 

Similar to Thu vien chuan c++

Stl vector nguyen_trihai_11520094_khmt06
Stl vector nguyen_trihai_11520094_khmt06Stl vector nguyen_trihai_11520094_khmt06
Stl vector nguyen_trihai_11520094_khmt06Quach Long
 
OOP_02_Java can ban.pdf
OOP_02_Java can ban.pdfOOP_02_Java can ban.pdf
OOP_02_Java can ban.pdfssuserd01a5c
 
Oop unit 04 các kỹ thuật xây dựng lớp
Oop unit 04 các kỹ thuật xây dựng lớpOop unit 04 các kỹ thuật xây dựng lớp
Oop unit 04 các kỹ thuật xây dựng lớpTráng Hà Viết
 
Oop unit 05 một số kỹ thuật java nâng cao
Oop unit 05 một số kỹ thuật java nâng caoOop unit 05 một số kỹ thuật java nâng cao
Oop unit 05 một số kỹ thuật java nâng caoTráng Hà Viết
 
Lớp 11 --chương 4 -- bài 11 --Kiểu mảng
Lớp 11 --chương 4 -- bài 11 --Kiểu mảngLớp 11 --chương 4 -- bài 11 --Kiểu mảng
Lớp 11 --chương 4 -- bài 11 --Kiểu mảngHoàng Kỳ Anh
 
CTDL-04-Ngan xep va Hang doi (1).pdf
CTDL-04-Ngan xep va Hang doi (1).pdfCTDL-04-Ngan xep va Hang doi (1).pdf
CTDL-04-Ngan xep va Hang doi (1).pdfLmTrn286060
 
Ky thuat l.trinh_java
Ky thuat l.trinh_javaKy thuat l.trinh_java
Ky thuat l.trinh_javaLam Man
 
Tóm tắt các hàm chuẩn của c
Tóm tắt các hàm chuẩn của cTóm tắt các hàm chuẩn của c
Tóm tắt các hàm chuẩn của cHồ Lợi
 
Ctdl lab07-cac thuat-toan_sap_xep
Ctdl lab07-cac thuat-toan_sap_xepCtdl lab07-cac thuat-toan_sap_xep
Ctdl lab07-cac thuat-toan_sap_xepNguyễn Ngọc Hà
 
[Cntt] bài giảng lập trình java bkhcm
[Cntt] bài giảng lập trình java   bkhcm[Cntt] bài giảng lập trình java   bkhcm
[Cntt] bài giảng lập trình java bkhcmHong Phuoc Nguyen
 
Bai5 dsachlket
Bai5 dsachlketBai5 dsachlket
Bai5 dsachlketHồ Lợi
 
LTJAVA_TV_Slides.ppt
LTJAVA_TV_Slides.pptLTJAVA_TV_Slides.ppt
LTJAVA_TV_Slides.pptssuserf603dc1
 
Bai thi Nghiem ky thuat dien tu
Bai thi Nghiem ky thuat dien tuBai thi Nghiem ky thuat dien tu
Bai thi Nghiem ky thuat dien tuBrand Xanh
 
JavaEE Basic_Chapter4: Servlet Nâng Cao
JavaEE Basic_Chapter4: Servlet Nâng CaoJavaEE Basic_Chapter4: Servlet Nâng Cao
JavaEE Basic_Chapter4: Servlet Nâng CaoPhaolo Pham
 

Similar to Thu vien chuan c++ (20)

Stl vector nguyen_trihai_11520094_khmt06
Stl vector nguyen_trihai_11520094_khmt06Stl vector nguyen_trihai_11520094_khmt06
Stl vector nguyen_trihai_11520094_khmt06
 
[Cntt] all java
[Cntt] all java[Cntt] all java
[Cntt] all java
 
OOP_02_Java can ban.pdf
OOP_02_Java can ban.pdfOOP_02_Java can ban.pdf
OOP_02_Java can ban.pdf
 
Oop unit 04 các kỹ thuật xây dựng lớp
Oop unit 04 các kỹ thuật xây dựng lớpOop unit 04 các kỹ thuật xây dựng lớp
Oop unit 04 các kỹ thuật xây dựng lớp
 
Chuong 05
Chuong 05Chuong 05
Chuong 05
 
C đến C++ phần 1
C đến C++ phần 1C đến C++ phần 1
C đến C++ phần 1
 
Chuong 05 mang, con tro, tham chieu
Chuong 05 mang, con tro, tham chieuChuong 05 mang, con tro, tham chieu
Chuong 05 mang, con tro, tham chieu
 
Oop unit 05 một số kỹ thuật java nâng cao
Oop unit 05 một số kỹ thuật java nâng caoOop unit 05 một số kỹ thuật java nâng cao
Oop unit 05 một số kỹ thuật java nâng cao
 
Lớp 11 --chương 4 -- bài 11 --Kiểu mảng
Lớp 11 --chương 4 -- bài 11 --Kiểu mảngLớp 11 --chương 4 -- bài 11 --Kiểu mảng
Lớp 11 --chương 4 -- bài 11 --Kiểu mảng
 
CTDL-04-Ngan xep va Hang doi (1).pdf
CTDL-04-Ngan xep va Hang doi (1).pdfCTDL-04-Ngan xep va Hang doi (1).pdf
CTDL-04-Ngan xep va Hang doi (1).pdf
 
Ky thuat l.trinh_java
Ky thuat l.trinh_javaKy thuat l.trinh_java
Ky thuat l.trinh_java
 
Tóm tắt các hàm chuẩn của c
Tóm tắt các hàm chuẩn của cTóm tắt các hàm chuẩn của c
Tóm tắt các hàm chuẩn của c
 
Ctdl lab07-cac thuat-toan_sap_xep
Ctdl lab07-cac thuat-toan_sap_xepCtdl lab07-cac thuat-toan_sap_xep
Ctdl lab07-cac thuat-toan_sap_xep
 
[Cntt] bài giảng lập trình java bkhcm
[Cntt] bài giảng lập trình java   bkhcm[Cntt] bài giảng lập trình java   bkhcm
[Cntt] bài giảng lập trình java bkhcm
 
Bai5 dsachlket
Bai5 dsachlketBai5 dsachlket
Bai5 dsachlket
 
LINQ
LINQLINQ
LINQ
 
Chuong1 c
Chuong1 c Chuong1 c
Chuong1 c
 
LTJAVA_TV_Slides.ppt
LTJAVA_TV_Slides.pptLTJAVA_TV_Slides.ppt
LTJAVA_TV_Slides.ppt
 
Bai thi Nghiem ky thuat dien tu
Bai thi Nghiem ky thuat dien tuBai thi Nghiem ky thuat dien tu
Bai thi Nghiem ky thuat dien tu
 
JavaEE Basic_Chapter4: Servlet Nâng Cao
JavaEE Basic_Chapter4: Servlet Nâng CaoJavaEE Basic_Chapter4: Servlet Nâng Cao
JavaEE Basic_Chapter4: Servlet Nâng Cao
 

More from Tiến Quang Phan (18)

Windows comunication foundation
Windows comunication foundationWindows comunication foundation
Windows comunication foundation
 
VBA for AutoCAD
VBA for AutoCADVBA for AutoCAD
VBA for AutoCAD
 
Mainboard
MainboardMainboard
Mainboard
 
Keyboard shortcuts for windows 8 pdf
Keyboard shortcuts for windows 8 pdfKeyboard shortcuts for windows 8 pdf
Keyboard shortcuts for windows 8 pdf
 
C9 templates
C9 templatesC9 templates
C9 templates
 
C8 object-oriented thinking
C8 object-oriented thinkingC8 object-oriented thinking
C8 object-oriented thinking
 
C7 class relationship
C7 class relationshipC7 class relationship
C7 class relationship
 
C5 classes and objects
C5 classes and objectsC5 classes and objects
C5 classes and objects
 
C4 data structures
C4 data structuresC4 data structures
C4 data structures
 
C3 functions and_library
C3 functions and_libraryC3 functions and_library
C3 functions and_library
 
C2 basics of_c_and_cpp
C2 basics of_c_and_cppC2 basics of_c_and_cpp
C2 basics of_c_and_cpp
 
C1 introduction
C1 introductionC1 introduction
C1 introduction
 
C10 generic algorithms
C10 generic algorithmsC10 generic algorithms
C10 generic algorithms
 
Ngon ngu lap trinh c&c++
Ngon ngu lap trinh c&c++Ngon ngu lap trinh c&c++
Ngon ngu lap trinh c&c++
 
Nang cao c++
Nang cao c++Nang cao c++
Nang cao c++
 
Giao trinh c can ban
Giao trinh c can banGiao trinh c can ban
Giao trinh c can ban
 
Con tro ham c++
Con tro ham c++Con tro ham c++
Con tro ham c++
 
Bai tap oop c++
Bai tap oop c++Bai tap oop c++
Bai tap oop c++
 

Recently uploaded

Giới thiệu Dự án Sản Phụ Khoa - Y Học Cộng Đồng
Giới thiệu Dự án Sản Phụ Khoa - Y Học Cộng ĐồngGiới thiệu Dự án Sản Phụ Khoa - Y Học Cộng Đồng
Giới thiệu Dự án Sản Phụ Khoa - Y Học Cộng ĐồngYhoccongdong.com
 
CD21 Exercise 2.1 KEY.docx tieng anh cho
CD21 Exercise 2.1 KEY.docx tieng anh choCD21 Exercise 2.1 KEY.docx tieng anh cho
CD21 Exercise 2.1 KEY.docx tieng anh chonamc250
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI DẠY BUỔI 2) - TIẾNG ANH 7 GLOBAL SUCCESS (2 CỘ...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI DẠY BUỔI 2) - TIẾNG ANH 7 GLOBAL SUCCESS (2 CỘ...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI DẠY BUỔI 2) - TIẾNG ANH 7 GLOBAL SUCCESS (2 CỘ...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI DẠY BUỔI 2) - TIẾNG ANH 7 GLOBAL SUCCESS (2 CỘ...Nguyen Thanh Tu Collection
 
TỔNG HỢP ĐỀ THI CHÍNH THỨC KỲ THI TUYỂN SINH VÀO LỚP 10 THPT MÔN NGỮ VĂN NĂM ...
TỔNG HỢP ĐỀ THI CHÍNH THỨC KỲ THI TUYỂN SINH VÀO LỚP 10 THPT MÔN NGỮ VĂN NĂM ...TỔNG HỢP ĐỀ THI CHÍNH THỨC KỲ THI TUYỂN SINH VÀO LỚP 10 THPT MÔN NGỮ VĂN NĂM ...
TỔNG HỢP ĐỀ THI CHÍNH THỨC KỲ THI TUYỂN SINH VÀO LỚP 10 THPT MÔN NGỮ VĂN NĂM ...Nguyen Thanh Tu Collection
 
Các điều kiện bảo hiểm trong bảo hiểm hàng hoá
Các điều kiện bảo hiểm trong bảo hiểm hàng hoáCác điều kiện bảo hiểm trong bảo hiểm hàng hoá
Các điều kiện bảo hiểm trong bảo hiểm hàng hoámyvh40253
 
Chuong trinh dao tao Su pham Khoa hoc tu nhien, ma nganh - 7140247.pdf
Chuong trinh dao tao Su pham Khoa hoc tu nhien, ma nganh - 7140247.pdfChuong trinh dao tao Su pham Khoa hoc tu nhien, ma nganh - 7140247.pdf
Chuong trinh dao tao Su pham Khoa hoc tu nhien, ma nganh - 7140247.pdfhoangtuansinh1
 
SÁNG KIẾN ÁP DỤNG CLT (COMMUNICATIVE LANGUAGE TEACHING) VÀO QUÁ TRÌNH DẠY - H...
SÁNG KIẾN ÁP DỤNG CLT (COMMUNICATIVE LANGUAGE TEACHING) VÀO QUÁ TRÌNH DẠY - H...SÁNG KIẾN ÁP DỤNG CLT (COMMUNICATIVE LANGUAGE TEACHING) VÀO QUÁ TRÌNH DẠY - H...
SÁNG KIẾN ÁP DỤNG CLT (COMMUNICATIVE LANGUAGE TEACHING) VÀO QUÁ TRÌNH DẠY - H...Nguyen Thanh Tu Collection
 
Campbell _2011_ - Sinh học - Tế bào - Ref.pdf
Campbell _2011_ - Sinh học - Tế bào - Ref.pdfCampbell _2011_ - Sinh học - Tế bào - Ref.pdf
Campbell _2011_ - Sinh học - Tế bào - Ref.pdfTrnHoa46
 
BỘ LUYỆN NGHE VÀO 10 TIẾNG ANH DẠNG TRẮC NGHIỆM 4 CÂU TRẢ LỜI - CÓ FILE NGHE.pdf
BỘ LUYỆN NGHE VÀO 10 TIẾNG ANH DẠNG TRẮC NGHIỆM 4 CÂU TRẢ LỜI - CÓ FILE NGHE.pdfBỘ LUYỆN NGHE VÀO 10 TIẾNG ANH DẠNG TRẮC NGHIỆM 4 CÂU TRẢ LỜI - CÓ FILE NGHE.pdf
BỘ LUYỆN NGHE VÀO 10 TIẾNG ANH DẠNG TRẮC NGHIỆM 4 CÂU TRẢ LỜI - CÓ FILE NGHE.pdfNguyen Thanh Tu Collection
 
1.DOANNGOCPHUONGTHAO-APDUNGSTEMTHIETKEBTHHHGIUPHSHOCHIEUQUA (1).docx
1.DOANNGOCPHUONGTHAO-APDUNGSTEMTHIETKEBTHHHGIUPHSHOCHIEUQUA (1).docx1.DOANNGOCPHUONGTHAO-APDUNGSTEMTHIETKEBTHHHGIUPHSHOCHIEUQUA (1).docx
1.DOANNGOCPHUONGTHAO-APDUNGSTEMTHIETKEBTHHHGIUPHSHOCHIEUQUA (1).docxTHAO316680
 
GIÁO TRÌNH KHỐI NGUỒN CÁC LOẠI - ĐIỆN LẠNH BÁCH KHOA HÀ NỘI
GIÁO TRÌNH  KHỐI NGUỒN CÁC LOẠI - ĐIỆN LẠNH BÁCH KHOA HÀ NỘIGIÁO TRÌNH  KHỐI NGUỒN CÁC LOẠI - ĐIỆN LẠNH BÁCH KHOA HÀ NỘI
GIÁO TRÌNH KHỐI NGUỒN CÁC LOẠI - ĐIỆN LẠNH BÁCH KHOA HÀ NỘIĐiện Lạnh Bách Khoa Hà Nội
 
ĐỀ CHÍNH THỨC KỲ THI TUYỂN SINH VÀO LỚP 10 THPT CÁC TỈNH THÀNH NĂM HỌC 2020 –...
ĐỀ CHÍNH THỨC KỲ THI TUYỂN SINH VÀO LỚP 10 THPT CÁC TỈNH THÀNH NĂM HỌC 2020 –...ĐỀ CHÍNH THỨC KỲ THI TUYỂN SINH VÀO LỚP 10 THPT CÁC TỈNH THÀNH NĂM HỌC 2020 –...
ĐỀ CHÍNH THỨC KỲ THI TUYỂN SINH VÀO LỚP 10 THPT CÁC TỈNH THÀNH NĂM HỌC 2020 –...Nguyen Thanh Tu Collection
 
Kiểm tra cuối học kì 1 sinh học 12 đề tham khảo
Kiểm tra cuối học kì 1 sinh học 12 đề tham khảoKiểm tra cuối học kì 1 sinh học 12 đề tham khảo
Kiểm tra cuối học kì 1 sinh học 12 đề tham khảohoanhv296
 
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...Nguyen Thanh Tu Collection
 
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...Nguyen Thanh Tu Collection
 
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...Nguyen Thanh Tu Collection
 
Đề cương môn giải phẫu......................
Đề cương môn giải phẫu......................Đề cương môn giải phẫu......................
Đề cương môn giải phẫu......................TrnHoa46
 
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...Nguyen Thanh Tu Collection
 
PHƯƠNG THỨC VẬN TẢI ĐƯỜNG SẮT TRONG VẬN TẢI
PHƯƠNG THỨC VẬN TẢI ĐƯỜNG SẮT TRONG VẬN TẢIPHƯƠNG THỨC VẬN TẢI ĐƯỜNG SẮT TRONG VẬN TẢI
PHƯƠNG THỨC VẬN TẢI ĐƯỜNG SẮT TRONG VẬN TẢImyvh40253
 

Recently uploaded (20)

Giới thiệu Dự án Sản Phụ Khoa - Y Học Cộng Đồng
Giới thiệu Dự án Sản Phụ Khoa - Y Học Cộng ĐồngGiới thiệu Dự án Sản Phụ Khoa - Y Học Cộng Đồng
Giới thiệu Dự án Sản Phụ Khoa - Y Học Cộng Đồng
 
CD21 Exercise 2.1 KEY.docx tieng anh cho
CD21 Exercise 2.1 KEY.docx tieng anh choCD21 Exercise 2.1 KEY.docx tieng anh cho
CD21 Exercise 2.1 KEY.docx tieng anh cho
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI DẠY BUỔI 2) - TIẾNG ANH 7 GLOBAL SUCCESS (2 CỘ...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI DẠY BUỔI 2) - TIẾNG ANH 7 GLOBAL SUCCESS (2 CỘ...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI DẠY BUỔI 2) - TIẾNG ANH 7 GLOBAL SUCCESS (2 CỘ...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI DẠY BUỔI 2) - TIẾNG ANH 7 GLOBAL SUCCESS (2 CỘ...
 
TỔNG HỢP ĐỀ THI CHÍNH THỨC KỲ THI TUYỂN SINH VÀO LỚP 10 THPT MÔN NGỮ VĂN NĂM ...
TỔNG HỢP ĐỀ THI CHÍNH THỨC KỲ THI TUYỂN SINH VÀO LỚP 10 THPT MÔN NGỮ VĂN NĂM ...TỔNG HỢP ĐỀ THI CHÍNH THỨC KỲ THI TUYỂN SINH VÀO LỚP 10 THPT MÔN NGỮ VĂN NĂM ...
TỔNG HỢP ĐỀ THI CHÍNH THỨC KỲ THI TUYỂN SINH VÀO LỚP 10 THPT MÔN NGỮ VĂN NĂM ...
 
Các điều kiện bảo hiểm trong bảo hiểm hàng hoá
Các điều kiện bảo hiểm trong bảo hiểm hàng hoáCác điều kiện bảo hiểm trong bảo hiểm hàng hoá
Các điều kiện bảo hiểm trong bảo hiểm hàng hoá
 
Chuong trinh dao tao Su pham Khoa hoc tu nhien, ma nganh - 7140247.pdf
Chuong trinh dao tao Su pham Khoa hoc tu nhien, ma nganh - 7140247.pdfChuong trinh dao tao Su pham Khoa hoc tu nhien, ma nganh - 7140247.pdf
Chuong trinh dao tao Su pham Khoa hoc tu nhien, ma nganh - 7140247.pdf
 
SÁNG KIẾN ÁP DỤNG CLT (COMMUNICATIVE LANGUAGE TEACHING) VÀO QUÁ TRÌNH DẠY - H...
SÁNG KIẾN ÁP DỤNG CLT (COMMUNICATIVE LANGUAGE TEACHING) VÀO QUÁ TRÌNH DẠY - H...SÁNG KIẾN ÁP DỤNG CLT (COMMUNICATIVE LANGUAGE TEACHING) VÀO QUÁ TRÌNH DẠY - H...
SÁNG KIẾN ÁP DỤNG CLT (COMMUNICATIVE LANGUAGE TEACHING) VÀO QUÁ TRÌNH DẠY - H...
 
Campbell _2011_ - Sinh học - Tế bào - Ref.pdf
Campbell _2011_ - Sinh học - Tế bào - Ref.pdfCampbell _2011_ - Sinh học - Tế bào - Ref.pdf
Campbell _2011_ - Sinh học - Tế bào - Ref.pdf
 
BỘ LUYỆN NGHE VÀO 10 TIẾNG ANH DẠNG TRẮC NGHIỆM 4 CÂU TRẢ LỜI - CÓ FILE NGHE.pdf
BỘ LUYỆN NGHE VÀO 10 TIẾNG ANH DẠNG TRẮC NGHIỆM 4 CÂU TRẢ LỜI - CÓ FILE NGHE.pdfBỘ LUYỆN NGHE VÀO 10 TIẾNG ANH DẠNG TRẮC NGHIỆM 4 CÂU TRẢ LỜI - CÓ FILE NGHE.pdf
BỘ LUYỆN NGHE VÀO 10 TIẾNG ANH DẠNG TRẮC NGHIỆM 4 CÂU TRẢ LỜI - CÓ FILE NGHE.pdf
 
1.DOANNGOCPHUONGTHAO-APDUNGSTEMTHIETKEBTHHHGIUPHSHOCHIEUQUA (1).docx
1.DOANNGOCPHUONGTHAO-APDUNGSTEMTHIETKEBTHHHGIUPHSHOCHIEUQUA (1).docx1.DOANNGOCPHUONGTHAO-APDUNGSTEMTHIETKEBTHHHGIUPHSHOCHIEUQUA (1).docx
1.DOANNGOCPHUONGTHAO-APDUNGSTEMTHIETKEBTHHHGIUPHSHOCHIEUQUA (1).docx
 
GIÁO TRÌNH KHỐI NGUỒN CÁC LOẠI - ĐIỆN LẠNH BÁCH KHOA HÀ NỘI
GIÁO TRÌNH  KHỐI NGUỒN CÁC LOẠI - ĐIỆN LẠNH BÁCH KHOA HÀ NỘIGIÁO TRÌNH  KHỐI NGUỒN CÁC LOẠI - ĐIỆN LẠNH BÁCH KHOA HÀ NỘI
GIÁO TRÌNH KHỐI NGUỒN CÁC LOẠI - ĐIỆN LẠNH BÁCH KHOA HÀ NỘI
 
ĐỀ CHÍNH THỨC KỲ THI TUYỂN SINH VÀO LỚP 10 THPT CÁC TỈNH THÀNH NĂM HỌC 2020 –...
ĐỀ CHÍNH THỨC KỲ THI TUYỂN SINH VÀO LỚP 10 THPT CÁC TỈNH THÀNH NĂM HỌC 2020 –...ĐỀ CHÍNH THỨC KỲ THI TUYỂN SINH VÀO LỚP 10 THPT CÁC TỈNH THÀNH NĂM HỌC 2020 –...
ĐỀ CHÍNH THỨC KỲ THI TUYỂN SINH VÀO LỚP 10 THPT CÁC TỈNH THÀNH NĂM HỌC 2020 –...
 
1 - MÃ LỖI SỬA CHỮA BOARD MẠCH BẾP TỪ.pdf
1 - MÃ LỖI SỬA CHỮA BOARD MẠCH BẾP TỪ.pdf1 - MÃ LỖI SỬA CHỮA BOARD MẠCH BẾP TỪ.pdf
1 - MÃ LỖI SỬA CHỮA BOARD MẠCH BẾP TỪ.pdf
 
Kiểm tra cuối học kì 1 sinh học 12 đề tham khảo
Kiểm tra cuối học kì 1 sinh học 12 đề tham khảoKiểm tra cuối học kì 1 sinh học 12 đề tham khảo
Kiểm tra cuối học kì 1 sinh học 12 đề tham khảo
 
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
 
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
 
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
 
Đề cương môn giải phẫu......................
Đề cương môn giải phẫu......................Đề cương môn giải phẫu......................
Đề cương môn giải phẫu......................
 
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
 
PHƯƠNG THỨC VẬN TẢI ĐƯỜNG SẮT TRONG VẬN TẢI
PHƯƠNG THỨC VẬN TẢI ĐƯỜNG SẮT TRONG VẬN TẢIPHƯƠNG THỨC VẬN TẢI ĐƯỜNG SẮT TRONG VẬN TẢI
PHƯƠNG THỨC VẬN TẢI ĐƯỜNG SẮT TRONG VẬN TẢI
 

Thu vien chuan c++

  • 1. © 2003 Prentice Hall, Inc. All rights reserved. 1 Thư viện chuẩn C++ Standard Template Library (STL) © 2003 Prentice Hall, Inc. All rights reserved. 2 Tổng quan • 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ức độ nào đó) <algorithm> <bitset> <complex> <deque> <exception> <fstream> <functional> <iomanip> <ios> <iosfwd> <iostream> <istream> <iterator> <limits> <list> <locale> <stack> <stdexcept> <streambuf> <string> <typeinfo> <utility> <valarray> <vector> <map> <memory> <new> <numeric> <ostream> <queue> <set> <sstream> © 2003 Prentice Hall, Inc. All rights reserved. 3 Thư viện khuôn mẫu chuẩn - STL • Thư viện chuẩn C++ gồm 2 phần: – Lớp string – Thư viện khuôn mẫu chuẩn – STL • Ngoại trừ lớp string, tất cả các thành phần còn lại của thư viện đều là các khuôn mẫu • Tác giả đầu tiên của STL là Alexander Stepanov, mục đích của ông là xây dựng một cách thể hiện tư tưởng lập trình tổng quát • Các khái niệm trong STL được phát triển độc lập với C++ – Do đó, ban đầu, STL không phải là một thư viện C++, mà nó đã được chuyển đổi thành thư viện C++ – Nhiều tư tưởng dẫn đến sự phát triển của STL đã được cài đặt phần nào trong Scheme, Ada, và C © 2003 Prentice Hall, Inc. All rights reserved. 4 Thư viện khuôn mẫu chuẩn - STL • Một số lời khuyên về STL – 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 – Từ tư tưởng lập trình tổng quát dẫn tới những "khối cơ bản" (building block) mà có thể kết hợp với nhau theo đủ kiểu – Tuy làm quen với STL tốn không ít thời gian nhưng thành quả tiềm tàng về năng xuất rất xứng đáng với thời gian đầu tư – 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
  • 2. © 2003 Prentice Hall, Inc. All rights reserved. 5 Giới thiệu Standard Template Library (STL) • Ba thành phần chính của STL – Các thành phần rất mạnh xây dựng dựa trên template • 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 tử dữ liệu của các container • Algorithm: các thuật toán để thao tác dữ liệu, tìm kiếm, sắp xếp, v.v.. © 2003 Prentice Hall, Inc. All rights reserved. 6 Giới thiệu về các Container • 3 loại container – Sequence container – container chuỗi • các cấu trúc dữ liệu tuyến tính (vector, danh sách liên kết) • first-class container • vector, deque, list – Associative container – container liên kết • các cấu trúc phi tuyến, có thể tìm phần tử nhanh chóng • first-class container • các cặp khóa/giá trị • set, multiset, map, multimap – Container adapter – các bộ tương thích container • stack, queue, priority_queue © 2003 Prentice Hall, Inc. All rights reserved. 7 Các hàm thành viên STL • Các hàm thành viên mọi container đều có – Default constructor, copy constructor, destructor – empty – max_size, size – = < <= > >= == != – swap • Các hàm thành viên của first-class container – begin, end – rbegin, rend – erase, clear © 2003 Prentice Hall, Inc. All rights reserved. 8 Giới thiệu về Iterator • Iterator tương tự như con trỏ – trỏ tới các phần tử trong một container – các toán tử iterator cho mọi container • * truy nhập phần tử được trỏ tới • ++ trỏ tới phần tử tiếp theo • begin() trả về iterator trỏ tới phần tử đầu tiên • end() trả về iterator trỏ tới phần tử đặc biệt chặn cuối container
  • 3. © 2003 Prentice Hall, Inc. All rights reserved. 9 Các loại Iterator • Input (ví dụ: istream_iterator) – Đọc các phần tử từ một container, hỗ trợ ++,+= (chỉ tiến) • Output (ví dụ: ostream_iterator) – Ghi các phần tử vào container, hỗ trợ ++,+= (chỉ tiến) • Forward (ví dụ: hash_set<T> iterator) – Kết hợp input iterator và output iterator – Multi-pass (có thể duyệt chuỗi nhiều lần) • Bidirectional (Ví dụ: list<T> iterator) – Như forward iterator, nhưng có thể lùi (--,-=) • Random access (Ví dụ: vector<T> iterator) – Như bidirectional, nhưng còn có thể nhảy tới phần tử tùy ý © 2003 Prentice Hall, Inc. All rights reserved. 10 Các loại Iteratorđược hỗ trợ • Sequence container – vector: random access – deque: random access – list: bidirectional • Associative container (hỗ trợ các loại bidirectional) – set, multiset,map, multimap • Container adapter (không hỗ trợ iterator) – stack, queue, priority_queue © 2003 Prentice Hall, Inc. All rights reserved. 11 Các phép toán đối với Iterator • Input iterator ++ , =*p , -> , == , != • Output iterator ++ , *p= , p = p1 • Forward iterator – Kết hợp các toán tử của input và output iterator • Bidirectional iterator các toán tử cho forward, và -- • Random iterator các toán tử cho bidirectional, và + , +=, -, -=, >, >=, <, <=,[] © 2003 Prentice Hall, Inc. All rights reserved. 12 Giới thiệu các thuật toán – Algorithm • STL có các thuật toán được sử dụng tổng quát cho nhiều loại container – thao tác gián tiếp với các phần tử qua các iterator – thường dùng cho các phần tử trong một chuỗi • 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 – các thuật toán thường trả về iterator • ví dụ: find() trả về iterator trỏ tới phần tử cần tìm hoặc trả về end() nếu không tìm thấy – 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
  • 4. © 2003 Prentice Hall, Inc. All rights reserved. 13 Sequence Container • 3 loại sequence container: – vector – dựa theo mảng – deque – dựa theo mảng – list – danh sách liên kết hiệu quả cao © 2003 Prentice Hall, Inc. All rights reserved. 14 vector Sequence Container • vector – <vector> – cấu trúc dữ liệu với các vùng nhớ liên tiếp • truy nhập các phần tử bằng toán tử [] – sử dụng khi dữ liệu cần được sắp xếp và truy nhập dễ dàng • Cơ chế hoạt động khi hết bộ nhớ – cấp phát một vùng nhớ liên lục lớn hơn – tự sao chép ra vùng nhớ mới – trả lại vùng nhớ cũ • sử dụng random access iterator © 2003 Prentice Hall, Inc. All rights reserved. 15 vector Sequence Container • Khai báo – std::vector <type> v; • type là kiểu dữ liệu của phần tử dữ liệu (int, float, v.v..) • Iterator – std::vector<type>::iterator iterVar; • trường hợp thông thường – std::vector<type>::const_iterator iterVar; • const_iterator không thể sửa đổi các phần tử – std::vector<type>::reverse_iterator iterVar; • Visits elements in reverse order (end to beginning) • Use rbegin to get starting point • Use rend to get ending point © 2003 Prentice Hall, Inc. All rights reserved. 16 vector Sequence Container • Các hàm thành viên của vector – v.push_back(value) • thêm phần tử vào cuối (sequence container nào cũng có hàm này). – v.size() • kích thước hiện tại của vector – v.capacity() • kích thước có thể lưu trữ trước khi phải cấp phát lại • khi cấp phát lại sẽ cấp phát kích thước gấp đôi – vector<type> v(a, a + SIZE) • tạo vector v từ SIZE phần tử đầu tiên của mảng a
  • 5. © 2003 Prentice Hall, Inc. All rights reserved. 17 vector Sequence Container • Các hàm thành viên của vector – v.insert(iterator, value ) • chèn value vào trước vị trí của iterator – v.insert(iterator, array , array + SIZE) • chèn vào vector SIZE phần tử đầu tiên của mảng array – v.erase( iterator ) • xóa phần tử khỏi container – v.erase( iter1, iter2 ) • xóa bỏ các phần tử bắt đầu từ iter1 đến hết phần tử liền trước iter2 – v.clear() • Xóa toàn bộ container © 2003 Prentice Hall, Inc. All rights reserved. 18 21.2.1 vector Sequence Container • Các hàm thành viên của vector – v.front(), v.back() • Trả về phần tử đầu tiên và cuối cùng – v.[elementNumber] = value; • Gán giá trị value cho một phần tử – v.at[elementNumber] = value; • Như trên, nhưng kèm theo kiểm tra chỉ số hợp lệ • có thể ném ngoại lệ out_of_bounds © 2003 Prentice Hall, Inc. All rights reserved. Outline 19 fig21_14.cpp (1 of 3) 1 // Fig. 21.14: fig21_14.cpp 2 // Demonstrating standard library vector class template. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 #include <vector> // vector class-template definition 10 11 // prototype for function template printVector 12 template < class T > 13 void printVector( const std::vector< T > &integers2 ); 14 15 int main() 16 { 17 const int SIZE = 6; 18 int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 }; 19 20 std::vector< int > integers; 21 22 cout << "The initial size of integers is: " 23 << integers.size() 24 << "nThe initial capacity of integers is: " 25 << integers.capacity(); 26 Tạo một vector chứa các giá trị int Gọi các hàm thành viên. © 2003 Prentice Hall, Inc. All rights reserved. Outline 20 fig21_14.cpp (2 of 3) 27 // function push_back is in every sequence collection 28 integers.push_back( 2 ); 29 integers.push_back( 3 ); 30 integers.push_back( 4 ); 31 32 cout << "nThe size of integers is: " << integers.size() 33 << "nThe capacity of integers is: " 34 << integers.capacity(); 35 36 cout << "nnOutput array using pointer notation: "; 37 38 for ( int *ptr = array; ptr != array + SIZE; ++ptr ) 39 cout << *ptr << ' '; 40 41 cout << "nOutput vector using iterator notation: "; 42 printVector( integers ); 43 44 cout << "nReversed contents of vector integers: "; 45 sử dụng push_back để thêm phần tử vào cuối vector
  • 6. © 2003 Prentice Hall, Inc. All rights reserved. Outline 21 fig21_14.cpp (3 of 3) 46 std::vector< int >::reverse_iterator reverseIterator; 47 48 for ( reverseIterator = integers.rbegin(); 49 reverseIterator!= integers.rend(); 50 ++reverseIterator ) 51 cout << *reverseIterator << ' '; 52 53 cout << endl; 54 55 return 0; 56 57 } // end main 58 59 // function template for outputting vector elements 60 template < class T > 61 void printVector( const std::vector< T > &integers2 ) 62 { 63 std::vector< T >::const_iterator constIterator; 64 65 for ( constIterator = integers2.begin(); 66 constIterator != integers2.end(); 67 constIterator++ ) 68 cout << *constIterator << ' '; 69 70 } // end function printVector Duyệt ngược vector bằng một reverse_iterator. Template function để duyệt vector theo chiều tiến. © 2003 Prentice Hall, Inc. All rights reserved. Outline 22 fig21_14.cpp output (1 of 1) The initial size of v is: 0 The initial capacity of v is: 0 The size of v is: 3 The capacity of v is: 4 Contents of array a using pointer notation: 1 2 3 4 5 6 Contents of vector v using iterator notation: 2 3 4 Reversed contents of vector v: 4 3 2 © 2003 Prentice Hall, Inc. All rights reserved. Outline 23 fig21_15.cpp (1 of 3) 1 // Fig. 21.15: fig21_15.cpp 2 // Testing Standard Library vector class template 3 // element-manipulation functions. 4 #include <iostream> 5 6 using std::cout; 7 using std::endl; 8 9 #include <vector> // vector class-template definition 10 #include <algorithm> // copy algorithm 11 12 int main() 13 { 14 const int SIZE = 6; 15 int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 }; 16 17 std::vector< int > integers( array, array + SIZE ); 18 std::ostream_iterator< int > output( cout, " " ); 19 20 cout << "Vector integers contains: "; 21 std::copy( integers.begin(), integers.end(), output ); 22 23 cout << "nFirst element of integers: " << integers.front() 24 << "nLast element of integers: " << integers.back(); 25 Create vector (initialized using an array) and ostream_iterator. Copy range of iterators to output (ostream_iterator). © 2003 Prentice Hall, Inc. All rights reserved. Outline 24 fig21_15.cpp (2 of 3) 26 integers[ 0 ] = 7; // set first element to 7 27 integers.at( 2 ) = 10; // set element at position 2 to 10 28 29 // insert 22 as 2nd element 30 integers.insert( integers.begin() + 1, 22 ); 31 32 cout << "nnContents of vector integers after changes: " ; 33 std::copy( integers.begin(), integers.end(), output ); 34 35 // access out-of-range element 36 try { 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 << "nnException: " << outOfRange.what(); 44 45 } // end catch 46 47 // erase first element 48 integers.erase( integers.begin() ); 49 cout << "nnVector integers after erasing first element: " ; 50 std::copy( integers.begin(), integers.end(), output ); 51 More vector member functions. at has range checking, and can throw an exception.
  • 7. © 2003 Prentice Hall, Inc. All rights reserved. Outline 25 fig21_15.cpp (3 of 3) 52 // erase remaining elements 53 integers.erase( integers.begin(), integers.end() ); 54 cout << "nAfter erasing all elements, vector integers " 55 << ( integers.empty() ? "is" : "is not" ) << " empty"; 56 57 // insert elements from array 58 integers.insert( integers.begin(), array, array + SIZE ); 59 cout << "nnContents of vector integers before clear: "; 60 std::copy( integers.begin(), integers.end(), output ); 61 62 // empty integers; clear calls erase to empty a collection 63 integers.clear(); 64 cout << "nAfter clear, vector integers " 65 << ( integers.empty() ? "is" : "is not" ) << " empty"; 66 67 cout << endl; 68 69 return 0; 70 71 } // end main © 2003 Prentice Hall, Inc. All rights reserved. Outline 26 fig21_15.cpp output (1 of 1) Vector integers contains: 1 2 3 4 5 6 First element of integers: 1 Last element of integers: 6 Contents of vector integers after changes: 7 22 2 10 4 5 6 Exception: invalid vector<T> subscript Vector integers after erasing first element: 22 2 10 4 5 6 After erasing all elements, vector integers is empty Contents of vector integers before clear: 1 2 3 4 5 6 After clear, vector integers is empty © 2003 Prentice Hall, Inc. All rights reserved. 27 Container Adapter • Container adapter – stack, queue và priority_queue – Không phải first class container, cho nên • Không hỗ trợ iterator • Không cung cấp cấu trúc dữ liệu – Lập trình viên có thể chọn cách cài đặt (sử dụng cấu trúc dữ liệu nào) – đều cung cấp các hàm thành viên push và pop bên cạch các hàm thành viên khác. © 2003 Prentice Hall, Inc. All rights reserved. 28 stack Adapter • stack – Header <stack> – chèn và xóa tại một đầu – 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)
  • 8. © 2003 Prentice Hall, Inc. All rights reserved. Outline 29 fig21_23.cpp (1 of 3) 1 // Fig. 21.23: fig21_23.cpp 2 // Standard library adapter stack test program. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <stack> // stack adapter definition 9 #include <vector> // vector class-template definition 10 #include <list> // list class-template definition 11 12 // popElements function-template prototype 13 template< class T > 14 void popElements( T &stackRef ); 15 16 int main() 17 { 18 // stack with default underlying deque 19 std::stack< int > intDequeStack; 20 21 // stack with underlying vector 22 std::stack< int, std::vector< int > > intVectorStack; 23 24 // stack with underlying list 25 std::stack< int, std::list< int > > intListStack; 26 Tạo stack bằng nhiều kiểu cài đặt. © 2003 Prentice Hall, Inc. All rights reserved. Outline 30 fig21_23.cpp (2 of 3) 27 // push the values 0-9 onto each stack 28 for ( int i = 0; i < 10; ++i ) { 29 intDequeStack.push( i ); 30 intVectorStack.push( i ); 31 intListStack.push( i ); 32 33 } // end for 34 35 // display and remove elements from each stack 36 cout << "Popping from intDequeStack: "; 37 popElements( intDequeStack ); 38 cout << "nPopping from intVectorStack: "; 39 popElements( intVectorStack ); 40 cout << "nPopping from intListStack: "; 41 popElements( intListStack ); 42 43 cout << endl; 44 45 return 0; 46 47 } // end main 48 sử dụng hàm thành viên push. © 2003 Prentice Hall, Inc. All rights reserved. Outline 31 fig21_23.cpp (3 of 3) fig21_23.cpp output (1 of 1) 49 // pop elements from stack object to which stackRef refers 50 template< class T > 51 void popElements( T &stackRef ) 52 { 53 while ( !stackRef.empty() ) { 54 cout << stackRef.top() << ' '; // view top element 55 stackRef.pop(); // remove top element 56 57 } // end while 58 59 } // end function popElements Popping from intDequeStack: 9 8 7 6 5 4 3 2 1 0 Popping from intVectorStack: 9 8 7 6 5 4 3 2 1 0 Popping from intListStack: 9 8 7 6 5 4 3 2 1 0 © 2003 Prentice Hall, Inc. All rights reserved. 32 Các thuật toán • Trước STL – các thư viện của các hãng khác nhau không tương thích – Các thuật toán được xây dựng và gắn vào trong các lớp container • STL tách rời các container và các thuật toán – lợi thế: • dễ bổ sung các thuật toán mới • hiệu quả hơn, tránh các lời gọi hàm ảo – header <algorithm>
  • 9. © 2003 Prentice Hall, Inc. All rights reserved. 33 remove, remove_if, remove_copy và remove_copy_if • remove – remove( iter1, iter2, value); – Bỏ mọi phần tử có giá trị value trong khoảng (iter1- iter2) theo cách sau: • Chuyển các phần tử có giá trị value xuống cuối • không thay đổi kích thước của container hoặc thực sự xóa các phần tử – Trả về iterator tới kết thúc “mới” của container – các phần tử sau kết thúc mới là không xác định • remove_copy – 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. 34 remove, remove_if, remove_copy và remove_copy_if • remove_if – giống remove • trả về iterator tới phần tử cuối cùng • bỏ các phần tử mà hàm trả về true remove_if(iter1,iter2, function); • các phần tử được truyền cho function, hàm này trả về giá trị bool • remove_copy_if – giống remove_copy và remove_if remove_copy_if(iter1, iter2, iter3, function); © 2003 Prentice Hall, Inc. All rights reserved. 35 Các thuật toán toán học • random_shuffle(iter1, iter2) – xáo trộn các phần tử trong khoảng một cách ngẫu nhiên • count(iter1, iter2, value) – trả về số lần xuất hiện của value trong khoảng • count_if(iter1, iter2, function) – đếm số phần tử làm function trả về true • min_element(iter1, iter2) – trả về iterator tới phần tử nhỏ nhất • max_element(iter1, iter2) – trả về iterator tới phần tử lớn nhất © 2003 Prentice Hall, Inc. All rights reserved. 36 Các thuật toán toán học • accumulate(iter1, iter2) – trả về tổng các phần tử trong khoảng • for_each(iter1, iter2, function) – Gọi hàm function cho mỗi phần tử trong khoảng – không sửa đổi phần tử • transform(iter1, iter2, iter3, function) – gọi function cho mọi phần tử trong khoảng iter1-iter2, kết quả ghi vào iter3
  • 10. © 2003 Prentice Hall, Inc. All rights reserved. 37 Các thuật toán tìm kiếm và sắp xếp cơ bản • find(iter1, iter2, value) – trả về iterator tới lần xuất hiện đầu tiên (trong khoảng) của value • find_if(iter1, iter2, function) – như find – trả về iterator khi function trả về true • sort(iter1, iter2) – sắp xếp các phần tử theo thứ tự tăng dần • binary_search(iter1, iter2, value) – tìmgiá trị trong dãy sắp xếp tăng dần, – sử dụng thuật toán tìm kiếm nhị phân © 2003 Prentice Hall, Inc. All rights reserved. Outline 38 fig21_31.cpp (1 of 4) 1 // Fig. 21.31: fig21_31.cpp 2 // Standard library search and sort algorithms. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <algorithm> // algorithm definitions 9 #include <vector> // vector class-template definition 10 11 bool greater10( int value ); // prototype 12 13 int main() 14 { 15 const int SIZE = 10; 16 int a[ SIZE ] = { 10, 2, 17, 5, 16, 8, 13, 11, 20, 7 }; 17 18 std::vector< int > v( a, a + SIZE ); 19 std::ostream_iterator< int > output( cout, " " ); 20 21 cout << "Vector v contains: "; 22 std::copy( v.begin(), v.end(), output ); 23 24 // locate first occurrence of 16 in v 25 std::vector< int >::iterator location; 26 location = std::find( v.begin(), v.end(), 16 ); © 2003 Prentice Hall, Inc. All rights reserved. Outline 39 fig21_31.cpp (2 of 4) 27 28 if ( location != v.end() ) 29 cout << "nnFound 16 at location " 30 << ( location - v.begin() ); 31 else 32 cout << "nn16 not found"; 33 34 // locate first occurrence of 100 in v 35 location = std::find( v.begin(), v.end(), 100 ); 36 37 if ( location != v.end() ) 38 cout << "nFound 100 at location " 39 << ( location - v.begin() ); 40 else 41 cout << "n100 not found"; 42 43 // locate first occurrence of value greater than 10 in v 44 location = std::find_if( v.begin(), v.end(), greater10 ); 45 46 if ( location != v.end() ) 47 cout << "nnThe first value greater than 10 is " 48 << *location << "nfound at location " 49 << ( location - v.begin() ); 50 else 51 cout << "nnNo values greater than 10 were found"; 52 © 2003 Prentice Hall, Inc. All rights reserved. Outline 40 fig21_31.cpp (3 of 4) 53 // sort elements of v 54 std::sort( v.begin(), v.end() ); 55 56 cout << "nnVector v after sort: "; 57 std::copy( v.begin(), v.end(), output ); 58 59 // use binary_search to locate 13 in v 60 if ( std::binary_search( v.begin(), v.end(), 13 ) ) 61 cout << "nn13 was found in v"; 62 else 63 cout << "nn13 was not found in v"; 64 65 // use binary_search to locate 100 in v 66 if ( std::binary_search( v.begin(), v.end(), 100 ) ) 67 cout << "n100 was found in v"; 68 else 69 cout << "n100 was not found in v"; 70 71 cout << endl; 72 73 return 0; 74 75 } // end main 76
  • 11. © 2003 Prentice Hall, Inc. All rights reserved. Outline 41 fig21_31.cpp (4 of 4) fig21_31.cpp output (1 of 1) 77 // determine whether argument is greater than 10 78 bool greater10( int value ) 79 { 80 return value > 10; 81 82 } // end function greater10 Vector v contains: 10 2 17 5 16 8 13 11 20 7 Found 16 at location 4 100 not found The first value greater than 10 is 17 found at location 2 Vector v after sort: 2 5 7 8 10 11 13 16 17 20 13 was found in v 100 was not found in v © 2003 Prentice Hall, Inc. All rights reserved. 42 Function Object – functor • Function object (<functional>) – Các đối tượng có thể gọi như hàm bằng toán tử () 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 © 2003 Prentice Hall, Inc. All rights reserved. Outline 43 fig21_42.cpp (1 of 4) 1 // Fig. 21.42: fig21_42.cpp 2 // Demonstrating function objects. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <vector> // vector class-template definition 9 #include <algorithm> // copy algorithm 10 #include <numeric> // accumulate algorithm 11 #include <functional> // binary_function definition 12 13 // binary function adds square of its second argument and 14 // running total in its first argument, then returns sum 15 int sumSquares( int total, int value ) 16 { 17 return total + value * value; 18 19 } // end function sumSquares 20 Tạo một hàm để dùng với accumulate. © 2003 Prentice Hall, Inc. All rights reserved. Outline 44 fig21_42.cpp (2 of 4) 21 // binary function class template defines overloaded operator() 22 // that adds suare of its second argument and running total in 23 // its first argument, then returns sum 24 template< class T > 25 class SumSquaresClass : public std::binary_function< T, T, T > { 26 27 public: 28 29 // add square of value to total and return result 30 const T operator()( const T &total, const T &value ) 31 { 32 return total + value * value; 33 34 } // end function operator() 35 36 }; // end class SumSquaresClass 37 Tạo một function object (nó còn có thể đóng gói dữ liệu). Overload operator().
  • 12. © 2003 Prentice Hall, Inc. All rights reserved. Outline 45 fig21_42.cpp (3 of 4) 38 int main() 39 { 40 const int SIZE = 10; 41 int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 42 43 std::vector< int > integers( array, array + SIZE ); 44 45 std::ostream_iterator< int > output( cout, " " ); 46 47 int result = 0; 48 49 cout << "vector v contains:n"; 50 std::copy( integers.begin(), integers.end(), output ); 51 52 // calculate sum of squares of elements of vector integers 53 // using binary function sumSquares 54 result = std::accumulate( integers.begin(), integers.end(), 55 0, sumSquares ); 56 57 cout << "nnSum of squares of elements in integers using " 58 << "binarynfunction sumSquares: " << result; 59 đầu tiên, accumulate truyền 0 và phần tử thứ nhất lần lượt làm các tham số. Sau đó, nó dùng kếtquả trả về làm tham số thứ nhất, và lặp qua các phần tử còn lại. © 2003 Prentice Hall, Inc. All rights reserved. Outline 46 fig21_42.cpp (4 of 4) fig21_42.cpp output (1 of 1) 60 // calculate sum of squares of elements of vector integers 61 // using binary-function object 62 result = std::accumulate( integers.begin(), integers.end(), 63 0, SumSquaresClass< int >() ); 64 65 cout << "nnSum of squares of elements in integers using " 66 << "binarynfunction object of type " 67 << "SumSquaresClass< int >: " << result << endl; 68 69 return 0; 70 71 } // end main vector v contains: 1 2 3 4 5 6 7 8 9 10 Sum of squares of elements in integers using binary function sumSquares: 385 Sum of squares of elements in integers using binary function object of type SumSquaresClass< int >: 385 dùng accumulate với một function object.