You are on page 1of 45

Th vin chun C++ Standard Template Library (STL)

Th vin khun mu chun - STL


Th vin chun C++ bao gm 32 header file
<algorithm> <bitset> <complex> <deque> <exception> <fstream> <functional> <iomanip> <ios> <iosfwd> <iostream> <istream> <iterator> <limits> <list> <locale> <map> <memory> <new> <numeric> <ostream> <queue> <set> <sstream> <stack> <stdexcept> <streambuf> <string> <typeinfo> <utility> <valarray> <vector>

Th vin khun mu chun - STL


Th vin chun C++ gm 2 phn:
Lp string Th vin khun mu chun STL

Ngoi tr lp string, tt c cc thnh phn cn li ca th vin u l cc khun mu Tc gi u tin ca STL l Alexander Stepanov, mc ch ca ng l xy dng mt cch th hin t tng lp trnh tng qut

Th vin khun mu chun - STL


Cc khi nim trong STL c pht trin c lp vi C++
Do , ban u, STL khng phi l mt th vin C++, m n c chuyn i thnh th vin C++ Nhiu t tng dn n s pht trin ca STL c ci t phn no trong Scheme, Ada, v C

Th vin khun mu chun - STL


Mt s li khuyn v STL
STL c thit k p v hiu qu - khng c tha k hay hm o trong bt k nh ngha no T t tng lp trnh tng qut dn ti nhng "khi c bn" (building block) m c th kt hp vi nhau theo kiu Tuy lm quen vi STL tn khng t thi gian nhng thnh qu tim tng v nng xut rt xng ng vi thi gian u t Tm li hy hc v hy s dng!

Bi ging ny ch gii thiu mt phn rt nh ca STL

Gii thiu STL


Ba thnh phn chnh ca STL
Cc thnh phn rt mnh xy dng da trn template

Container: cc cu trc d liu template Iterator: ging con tr, dng truy nhp cc phn t d liu ca cc container Algorithm: cc thut ton thao tc d liu, tm kim, sp xp, v.v..

Gii thiu v cc Container


3 loi container
Sequence container container chui
cc cu trc d liu tuyn tnh (vector, danh sch lin kt) first-class container vector, deque, list

Associative container container lin kt


cc cu trc phi tuyn, c th tm phn t nhanh chng first-class container cc cp kha/gi tr set, multiset, map, multimap

Container adapter cc b tng thch container


stack, queue, priority_queue

Cc hm thnh vin STL


Cc hm thnh vin mi container u c
Default constructor, copy constructor, destructor empty max_size, size = < <= > >= == != swap

Cc hm thnh vin ca first-class container


begin, end rbegin, rend erase, clear

Gii thiu v Iterator


Iterator tng t nh con tr
tr ti cc phn t trong mt container cc ton t iterator cho mi container
* truy nhp phn t c tr ti ++ tr ti phn t tip theo begin() tr v iterator tr ti phn t u tin end() tr v iterator tr ti phn t c bit chn cui container

Cc loi Iterator
Input Output Forward (v d: istream_iterator) (v d: ostream_iterator) (v d: hash_set<T> iterator)
c cc phn t t mt container, h tr ++,+= (ch tin) Ghi cc phn t vo container, h tr ++,+= (ch tin) Kt hp input iterator v output iterator Multi-pass (c th duyt chui nhiu ln)

Bidirectional Randomaccess

(V d: list<T> iterator) (V d: vector<T> iterator)

Nh forward iterator, nhng c th li (--,-=) Nh bidirectional, nhng cn c th nhy ti phn t ty

Cc loi Iterator c h tr
Sequence container
vector: random access deque: random access list: bidirectional

Associative container (h tr cc loi bidirectional)


set, multiset,map, multimap

Container adapter (khng h tr iterator)


stack, queue, priority_queue

Cc php ton i vi Iterator


Input iterator
++ , =*p , -> , == , !=

Output iterator
++ , *p= , p = p1

Forward iterator
Kt hp cc ton t ca input v output iterator

Bidirectional iterator
cc ton t cho forward, v --

Random iterator
cc ton t cho bidirectional, v

+ , +=, -, -=, >, >=, <, <=,[]

Gii thiu cc thut ton Algorithm


STL c cc thut ton c s dng tng qut cho nhiu loi container
thao tc gin tip vi cc phn t qua cc iterator thng dng cho cc phn t trong mt chui
chui xc nh bi mt cp iterator tr ti phn t u tin v cui cng ca chui

cc thut ton thng tr v iterator


v d: find() tr v iterator tr ti phn t cn tm hoc tr v end() nu khng tm thy

s dng cc thut ton c cung cp gip lp trnh vin tit kim thi gian v cng sc

Sequence Container
3 loi sequence container:
vector da theo mng deque da theo mng list danh sch lin kt hiu qu cao

vector Sequence Container


vector
<vector> cu trc d liu vi cc vng nh lin tip
truy nhp cc phn t bng ton t [ ]

s dng khi d liu cn c sp xp v truy nhp d dng

Cch hot ng khi ht b nh


cp pht mt vng nh lin lc ln hn t sao chp ra vng nh mi tr li vng nh c

s dng randomaccess iterator

vector Sequence Container


Khai bo
std::vector <type> v;
type l kiu d liu ca phn t d liu (int, float, v.v..)

Iterator
std::vector<type>::iterator iterVar;
trng hp thng thng

std::vector<type>::const_iterator iterVar;
const_iterator khng th sa i cc phn 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

vector Sequence Container


Cc hm thnh vin ca vector
v.push_back(value)
thm phn t vo cui (sequence container no cng c hm ny).

v.size()
kch thc hin ti ca vector

v.capacity()
kch thc c th lu tr trc khi phi cp pht li khi cp pht li s cp pht kch thc gp i

vector<type> v(a, a + SIZE)


to vector vt SIZE phn t u tin ca mng a

vector Sequence Container


Cc hm thnh vin ca vector
v.insert(iterator, value )
chn value vo trc v tr ca iterator

v.insert(iterator, array , array + SIZE)


chn vo vector SIZE phn t u tin ca mng array

v.erase( iterator )
xa phn t khi container

v.erase( iter1, iter2 )


xa b cc phn t bt u t iter1 n ht phn t lin trc iter2

vector Sequence Container


Cc hm thnh vin ca vector
v.clear()
Xa ton b container

v.front(), v.back()
Tr v phn t u tin v cui cng

v.[elementNumber] = value;
Gn gi tr value cho mt phn t

v.at[elementNumber] = value;
Nh trn, nhng km theo kim tra ch s hp l c th nm ngoi l out_of_bounds

vector Sequence Container


ostream_iterator
std::ostream_iterator< type > Name( outputStream, separator );
type: outputs values of a certain type outputStream: iterator output location separator: character separating outputs

Example
std::ostream_iterator< int > output( cout, " " ); std::copy( iterator1, iterator2, output );

Copies elements from iterator1 up to (not including) iterator2 to output, an ostream_iterator


20

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

// Fig. 21.14: fig21_14.cpp // Demonstrating standard library vector class template. #include <iostream> using std::cout; using std::cin; using std::endl; #include <vector> // vector class-template definition

21

// prototype for function template printVector template < class T > void printVector( const std::vector< T > &integers2 ); int main() { const int SIZE = 6; To mt vector int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 };

cha

cc gi tr int

std::vector< int > integers; cout << << << <<

Gi cc hm thnh vin.

"The initial size of integers is: " integers.size() "\nThe initial capacity of integers is: " integers.capacity();

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

// function push_back integers.push_back( 2 integers.push_back( 3 integers.push_back( 4

is in every sequence collection ); s dng push_back ); thm phn t vo cui ); vector

22

cout << "\nThe size of integers is: " << integers.size() << "\nThe capacity of integers is: " << integers.capacity(); cout << "\n\nOutput array using pointer notation: "; for ( int *ptr = array; ptr != array + SIZE; ++ptr ) cout << *ptr << ' '; cout << "\nOutput vector using iterator notation: "; printVector( integers ); cout << "\nReversed contents of vector integers: ";

23
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 std::vector< int >::reverse_iterator reverseIterator; for ( reverseIterator = integers.rbegin(); reverseIterator!= integers.rend(); ++reverseIterator ) cout << *reverseIterator << ' '; cout << endl; return 0; } // end main // function template for outputting vector elements template < class T > void printVector( const std::vector< T > &integers2 ) { std::vector< T >::const_iterator constIterator; for ( constIterator = integers2.begin(); constIterator != integers2.end(); constIterator++ ) cout << *constIterator << ' '; } // end function printVector

fig21_14.cpp Duyt ngc vector bng (3 of 3) mt reverse_iterator.

Template function duyt vector theo chiu tin.

The The The The

initial size of v is: 0 initial capacity of v is: 0 size of v is: 3 capacity of v is: 4

24

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

fig21_14.cpp output (1 of 1)

Container Adapter
Container adapter
stack, queue v priority_queue Khng phi first class container, cho nn
Khng h tr iterator Khng cung cp cu trc d liu

Lp trnh vin c th chn cch ci t (s dng cu trc d liu no) u cung cp cc hm thnh vin push v pop bn cnh cc hm thnh vin khc.

stack Adapter
stack
Header <stack> chn v xa ti mt u Cu trc Last-in, first-out (LIFO) C th chn ci t bng vector, list, hoc deque (mc nh) Khai bo

stack<type, vector<type> > myStack;


stack<type, list<type> > myOtherStack; stack<type> anotherStack; // default deque chn ci t l vector, list hay deque khng lm thay i hnh vi, ch nh hng ti hiu qu (ci bng deque v vector l nhanh nht)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

// Fig. 21.23: fig21_23.cpp // Standard library adapter stack test program. #include <iostream> using std::cout; using std::endl; #include <stack> #include <vector> #include <list> // stack adapter definition // vector class-template definition // list class-template definition

27

fig21_23.cpp (1 of 3)

// popElements function-template prototype template< class T > void popElements( T &stackRef ); int main() { // stack with default underlying deque std::stack< int > intDequeStack;

To stack bng nhiu kiu ci t.

// stack with underlying vector std::stack< int, std::vector< int > > intVectorStack; // stack with underlying list std::stack< int, std::list< int > > intListStack;

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

// push the values 0-9 onto each stack for ( int i = 0; i < 10; ++i ) { intDequeStack.push( i ); intVectorStack.push( i ); intListStack.push( i ); } // end for

28

fig21_23.cpp s dng hm thnh vin push. (2 of 3)

// display and remove elements from each stack cout << "Popping from intDequeStack: "; popElements( intDequeStack ); cout << "\nPopping from intVectorStack: "; popElements( intVectorStack ); cout << "\nPopping from intListStack: "; popElements( intListStack ); cout << endl; return 0; } // end main

49 50 51 52 53 54 55 56 57 58 59

// pop elements from stack object to which stackRef refers template< class T > void popElements( T &stackRef ) { while ( !stackRef.empty() ) { cout << stackRef.top() << ' '; // view top element stackRef.pop(); // remove top element } // end while } // end function popElements

29

fig21_23.cpp (3 of 3) fig21_23.cpp output (1 of 1)

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

Cc thut ton
Trc STL
cc th vin ca cc hng khc nhau khng tng thch Cc thut ton c xy dng v gn vo trong cc lp container

STL tch ri cc container v cc thut ton


li th:
d b sung cc thut ton mi hiu qu hn, trnh cc li gi hm o

header <algorithm>

remove, remove_if, remove_copy v remove_copy_if


remove
remove( iter1, iter2, value); B mi phn t c gi tr value trong khong (iter1 - iter2) theo cch sau:
Chuyn cc phn t c gi tr value xung cui khng thay i kch thc ca container hoc thc s xa cc phn t

Tr v iterator ti kt thc mi ca container cc phn t sau kt thc mi l khng xc nh

remove, remove_if, remove_copy v remove_copy_if


remove_copy
remove_copy(iter1, iter2, iter3, value);
trong khong iter1-iter2, chp cc phn t khc value vo iter3 (output iterator)

remove_if
ging remove
tr v iterator ti phn t cui cng b cc phn t m hm tr v true

remove_if(iter1,iter2, function);
cc phn t c truyn cho function, hm ny tr v gi tr bool

remove, remove_if, remove_copy v remove_copy_if


remove_copy_if
ging remove_copy v remove_if remove_copy_if(iter1, iter2, iter3, function);

Cc thut ton ton hc


random_shuffle(iter1, iter2)
xo trn cc phn t trong khong mt cch ngu nhin

count(iter1, iter2, value)


tr v s ln xut hin ca value trong khong

count_if(iter1, iter2, function)


m s phn t lm function tr v true

min_element(iter1, iter2)
tr v iterator ti phn t nh nht

max_element(iter1, iter2)
tr v iterator ti phn t ln nht

Cc thut ton ton hc


accumulate(iter1, iter2)
tr v tng cc phn t trong khong

for_each(iter1, iter2, function)


Gi hm function cho mi phn t trong khong khng sa i phn t

transform(iter1, iter2, iter3, function)


gi function cho mi phn t trong khong iter1iter2, kt qu ghi vo iter3

Cc thut ton tm kim v sp xp c bn


find(iter1, iter2, value)
tr v iterator ti ln xut hin u tin (trong khong) ca value

find_if(iter1, iter2, function)


nh find tr v iterator khi function tr v true

sort(iter1, iter2)
sp xp cc phn t theo th t tng dn

binary_search(iter1, iter2, value)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

// Fig. 21.31: fig21_31.cpp // Standard library search and sort algorithms. #include <iostream> using std::cout; using std::endl; #include <algorithm> #include <vector> // algorithm definitions // vector class-template definition // prototype

37

fig21_31.cpp (1 of 4)

bool greater10( int value );

int main() { const int SIZE = 10; int a[ SIZE ] = { 10, 2, 17, 5, 16, 8, 13, 11, 20, 7 }; std::vector< int > v( a, a + SIZE ); std::ostream_iterator< int > output( cout, " " ); cout << "Vector v contains: "; std::copy( v.begin(), v.end(), output ); // locate first occurrence of 16 in v std::vector< int >::iterator location; location = std::find( v.begin(), v.end(), 16 );

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

38
if ( location != v.end() ) cout << "\n\nFound 16 at location " << ( location - v.begin() ); else cout << "\n\n16 not found"; // locate first occurrence of 100 in v location = std::find( v.begin(), v.end(), 100 ); if ( location != v.end() ) cout << "\nFound 100 at location " << ( location - v.begin() ); else cout << "\n100 not found"; // locate first occurrence of value greater than 10 in v location = std::find_if( v.begin(), v.end(), greater10 ); if ( location != v.end() ) cout << "\n\nThe first value greater than 10 is " << *location << "\nfound at location " << ( location - v.begin() ); else cout << "\n\nNo values greater than 10 were found";

fig21_31.cpp (2 of 4)

39
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 // sort elements of v std::sort( v.begin(), v.end() ); cout << "\n\nVector v after sort: "; std::copy( v.begin(), v.end(), output ); // use binary_search to locate 13 in v if ( std::binary_search( v.begin(), v.end(), 13 ) ) cout << "\n\n13 was found in v"; else cout << "\n\n13 was not found in v"; // use binary_search to locate 100 in v if ( std::binary_search( v.begin(), v.end(), 100 ) ) cout << "\n100 was found in v"; else cout << "\n100 was not found in v"; cout << endl; return 0; } // end main

fig21_31.cpp (3 of 4)

77 78 79 80 81 82

// determine whether argument is greater than 10 bool greater10( int value ) { return value > 10; } // end function greater10

40

fig21_31.cpp (4 of 4) fig21_31.cpp output (1 of 1)

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

Function Object functor (<functional>)


Ccitngcthginhhmbngtont()

ST func tion objects L divides< T > equal_to< T > greater< T > greater_equal< T > less< T > less_equal< T > logical_and< T > logical_not< T > logical_or< T > minus< T > modulus< T > negate< T > not_equal_to< T > plus< T > multiplies< T >

Type arithmetic relational relational relational relational relational logical logical logical arithmetic arithmetic arithmetic relational arithmetic arithmetic

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

// Fig. 21.42: fig21_42.cpp // Demonstrating function objects. #include <iostream> using std::cout; using std::endl; #include #include #include #include <vector> <algorithm> <numeric> <functional> // // // // vector class-template definition copy algorithm accumulate algorithm binary_function definition

fig21_42.cpp (1 of 4)

To mt hm dng // binary function adds square of its second argument and // running total in its first argument, then returns sum vi accumulate. int sumSquares( int total, int value ) { return total + value * value;
} // end function sumSquares

42

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

// binary function class template defines overloaded operator() // that adds suare of its second argument and running total in // its first argument, then returns sum template< class T > class SumSquaresClass : public std::binary_function< T, T, T > { public: // add square of value to total and return result const T operator()( const T &total, const T &value ) { return total + value * value; } // end function operator() }; // end class SumSquaresClass

fig21_42.cpp To mt function object (2 of 4)

(n cn c th ng gi d liu). Overload operator().

43

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

int main() { const int SIZE = 10; int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; std::vector< int > integers( array, array + SIZE ); std::ostream_iterator< int > output( cout, " " ); int result = 0; cout << "vector v contains:\n"; std::copy( integers.begin(), integers.end(), output ); // calculate sum of squares of elements of vector integers // using binary function sumSquares result = std::accumulate( integers.begin(), integers.end(), 0, sumSquares ); cout << "\n\nSum of squares of elements in integers using " << "binary\nfunction sumSquares: " << result;

fig21_42.cpp (3 of 4)

u tin, accumulate truyn 0 v phn t th nht ln lt lm cc tham s. Sau , n dng ktqu tr v lm tham s th nht, v lp qua cc phn t cn li.

44

60 61 62 63 64 65 66 67 68 69 70 71

// calculate sum of squares of elements of vector integers // using binary-function object result = std::accumulate( integers.begin(), integers.end(), 0, SumSquaresClass< int >() ); cout << "\n\nSum of squares of elements in integers using " << "binary\nfunction object of type " << "SumSquaresClass< int >: " << result << endl; return 0; } // end main

fig21_42.cpp (4 of 4) fig21_42.cpp output (1 of 1)

dng accumulate vi mt function object.

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

45

You might also like