90 likes | 230 Views
Algorithms and Functionals. Standard Template Library. Section 1.6.4, class notes, STL references. 1. Standard Template Library Features. Algorithms Functionals Containers Iterators. Algorithms. Include <algorithm> find , for_each , sort , min , max , etc Example: Lec10/alg.cpp.
E N D
Algorithms and Functionals Standard Template Library Section 1.6.4, class notes, STL references 1
Standard Template Library Features • Algorithms • Functionals • Containers • Iterators
Algorithms Include <algorithm> find, for_each, sort, min, max, etc Example: Lec10/alg.cpp PrintArray(A,ASize); sort(A, A+ASize); PrintArray(A,ASize); reverse(A, A+ASize); PrintArray(A,ASize); } void PrintArray(int *A, int Size) { for(int i=0; i< Size; i++) cout << A[i] << " "; } int main() { const int ASize = 8; int A[ASize] = {32, 4, 8, 62, 3, 42, 23, 9}; Output 32 4 8 62 3 42 23 9 3 4 8 9 23 32 42 62 62 42 32 23 9 8 4 3 3
for_each See files included from: /usr/local/include/c++/4.3.2/algorithm template<typename _InputIterator, typename _Function> _Function for_each(_InputIterator __first, _InputIterator __last, _Function __f) { __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_requires_valid_range(__first, __last); for (; __first != __last; ++__first) __f(*__first); return __f; } 4
for_each Simplified template<typename _InputIterator, typename _Function> _Function for_each(_InputIterator __first, _InputIterator __last, _Function __f) { __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_requires_valid_range(__first, __last); for (; __first != __last; ++__first) __f(*__first); return __f; } template<typename I, typename F> F for_each(I first, I last, F f) { for (; first != last; ++first) f(*first); return f; } 5
for_each Example • Lec10/fo.cpp • print is a function class • It overloads operator() class print { public: void operator()(int a) { cout << a << " "; } }; for_each(A, A+ASize, print()); cout << "\n"; sort(A, A+ASize); for_each(A, A+ASize, print()); cout << "\n"; reverse(A, A+ASize); for_each(A, A+ASize, print()); cout << "\n"; 6
Another Function Class Example • Lec10/fo2.cpp • Use a function object to sort in descending order class gt { public: bool operator()(int a, int b) { return a > b; } }; for_each(A, A+ASize, print()); cout << "\n"; sort(A, A+ASize, gt()); for_each(A, A+ASize, print()); cout << "\n"; Output 32 4 8 62 3 42 23 9 62 42 32 23 9 8 4 3 7
Functionals • They are function classes provided by STL • Include <funtional> • less, greater, etc • Example: Lec10/fo3.cpp for_each(A, A+ASize, print()); cout << "\n"; sort(A, A+ASize, greater<int>()); for_each(A, A+ASize, print()); cout << "\n"; Output 32 4 8 62 3 42 23 9 62 42 32 23 9 8 4 3 8