Beruflich Dokumente
Kultur Dokumente
Generic algorithms
Apply to a wide range of types
E.g., sorting integers (long) or intervals (long, long)
Implementations in C++
Rely on templates, interface-based polymorphism Algorithms are implemented as function templates Use types that model iterator concepts Iterators in turn give access to containers
CSE 332: C++ STL algorithms
Gives an explicit range (calculate its length how?) Assumes first is before last (can check how?) Note how caller checks for success changed: why?
CSE 332: C++ STL algorithms
How much did the find1 code need to change? One last problem
What if we want to apply this to a data structure whose ranges cant be traversed via simple pointers?
CSE 332: C++ STL algorithms
Any specific type that meets the requirements is a model of that concept
E.g., list<int>::iterator vs. char * in find Different abstractions (bi-linked list vs. array iterators) No inheritance-based relationship between them But both model iterator concept necessary for find
CSE 332: C++ STL algorithms
What other capabilities are required of the Iterator and T type parameters by the STL find algorithm ?
template <class Iterator, class T> Iterator find (Iterator first, Iterator last, const T & value) { while (first != last && *first != value) ++first; return first; }
CSE 332: C++ STL algorithms
=*p
=*p
=*p
->
->
->
*p=
*p=
*p=
++
++
++
++ --
== !=
== !=
== !=
i = 2; cout << i << " appears << count(v.begin(), v.end(), i) << " times in v" << endl; return 0;
return 0; } /* output: cdgill@hive> ./copytest Makefile Makefile2 copied input file: Makefile to output file: Makefile2 cdgill@hive> diff Makefile Makefile2 cdgill@hive> */
next_permutation algorithm
Generates a specific kind of reordering, called a permutation Can use to generate all possible orders of a given sequence
/* output is original: asdf sorted: adfs permutations: adsf afds afsd dafs dasf dfas dsfa fads fasd fsad fsda sadf sdfa sfad sfda */
inner_product algorithm
Computes the inner (also known as dot) product of two vectors: sum of the products of their respective elements
/* output is: v contains 1 2 3 2 the sum of the elements in v is 8 the inner product of v and itself is 18 */
Concluding Remarks
STL algorithms give you useful, generic functions
Combine easily with a variety of containers/iterators Support many common data structure manipulations
Finding and modifying values, re-ordering, numeric operations