Standard Template Library Section 1 6 4 class
Standard Template Library Section 1. 6. 4, class notes, STL references Algorithms and Functionals 1
Standard Template Library Features • Algorithms • Functionals • Containers • Iterators 2
Algorithms • Include <algorithm> – find, for_each, sort, min, max, etc – Example: Lec 10/alg. cpp Print. Array(A, ASize); sort(A, A+ASize); Print. Array(A, ASize); void Print. Array(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}; reverse(A, A+ASize); Print. Array(A, ASize); } 32 3 62 4 Output 62 3 42 4 8 8 42 9 23 32 32 23 9 23 42 8 9 62 4 3 3
for_each • See files included from: – /usr/local/include/c++/4. 3. 2/algorithm template<typename _Input. Iterator, typename _Function> _Function for_each(_Input. Iterator __first, _Input. Iterator __last, _Function __f) { __glibcxx_function_requires(_Input. Iterator. Concept<_Input. Ite rator>) __glibcxx_requires_valid_range(__first, __last); for (; __first != __last; ++__first) __f(*__first); return __f; } 4
for_each Simplified template<typename _Input. Iterator, typename _Function> _Function for_each(_Input. Iterator __first, _Input. Iterator __last, _Function __f) { __glibcxx_function_requires(_Input. Iterator. Concept<_Input. Iterator>) __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 • Lec 10/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 • Lec 10/fo 2. 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"; 32 4 62 42 8 Output 62 3 42 32 23 9 8 23 9 4 3 7
Functionals • They are function classes provided by STL – Include <funtional> – less, greater, etc – Example: Lec 10/fo 3. cpp for_each(A, A+ASize, print()); cout << "n"; sort(A, A+ASize, greater<int>()); for_each(A, A+ASize, print()); cout << "n"; 32 4 62 42 Output 62 3 42 8 32 23 9 8 23 9 4 3 8
- Slides: 8