Upload
leo-valentine
View
232
Download
0
Embed Size (px)
Citation preview
8/13/2019 17A C Algorithms.ppt
1/16
CSE 332: C++STL algorithms
C++ STL Algorithms
Genericalgorithms
Apply to a wide range of types E.g., sorting integers (long) or intervals (long, long)
Dont require inheritance relationships
Types substituted need not have a common base class
Need only to be models of the algorithms concept
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
8/13/2019 17A C Algorithms.ppt
2/16
8/13/2019 17A C Algorithms.ppt
3/16
CSE 332: C++STL algorithms
Linear Search with Ranges
First generalization (Austern, pp. 11): use a range
char *find1(char* first, char* last, char c){
while (first != last && *first != c)
++first;
return first;}
Gives an explicit range (calculate its length how?)
Assumes first is before last (can check how?)
Note how caller checks for success changed: why?
8/13/2019 17A C Algorithms.ppt
4/16
CSE 332: C++STL algorithms
General Requirements for Linear Search
Before we try to improve the algorithm further
Lets come up with a definition of what it needs to do
This helps to plan what to require and what to leave flexible
Any linear search implementation must offer a way to:
1.Indicate the sequenceover which search will occur2.Represent a position within the sequence
3.Advance to the next elementof the sequence
4.Detect the endof the sequence
5.Return a value as an indication of success or failure
Goal: meet these requirements flexibly and efficiently
8/13/2019 17A C Algorithms.ppt
5/16
CSE 332: C++STL algorithms
Linear Search over Parameterized Types
Second generalization: use templates toparameterize the function argument types
template
T*find2(T*first,T*last, constT &value){
while (first != last && *first != value)
++first;return first;
}
How much did the find1code need to change? One last problem
What if we want to apply this to a data structure whoseranges cant be traversed via simple pointers?
8/13/2019 17A C Algorithms.ppt
6/16
CSE 332: C++STL algorithms
Linear Search with Generic Iterators
Third generalization: separate iterator type parameter
The STLs linear search algorithm (Austern pp. 13):
template Iteratorfind(Iteratorfirst,Iteratorlast, const T& value) {
while (first != last && *first != value) ++first;return first;}
Our first generic algorithm Searches any one-dimensional sequence of elements Notice we did not throw an exception
Not found is a normal result, not an aberration
8/13/2019 17A C Algorithms.ppt
7/16CSE 332: C++STL algorithms
Algorithm Concepts and Models
Remember a conceptgives a set of type requirements Classify/categorize types (e.g., random access iterators)
Tells whether or not a type can or cannot be used with aparticular STL algorithm (get a compiler error if it cannot)
E.g., we couldnt use a linked list iterator in find1oreven find2
Any specific type that meets the requirements is amodelof that concept E.g., list::iteratorvs. 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
8/13/2019 17A C Algorithms.ppt
8/16CSE 332: C++STL algorithms
Concepts and Modeling, Continued What very basic concept does the last statement in
STL find, (return first;) assume?
Asked another way, what must be able to happen to firstwhen its returned from function find? Same requirement imposed by by-value iterator parameters
What othercapabilities are required of theIterator
and Ttype parameters by the STL find algorithm ?
template Iterator find (Iterator first, Iterator last,
const T & value) {while (first != last && *first != value) ++first;return first;
}
8/13/2019 17A C Algorithms.ppt
9/16CSE 332: C++STL algorithms
Matching an Algorithm to the Iterators it Needs
== != =
== !=== !=== !=Comparison
++ -- +- += -=
++ --++++++Iteration
*p=*p=*p=*p=Write
->
[]->->->Access
=*p=*p=*p=*pRead
Random
AccessBidirectionalForwardInputOutputCategory
What STL iterator category does findrequire?
8/13/2019 17A C Algorithms.ppt
10/16CSE 332: C++STL algorithms
Organization of Algorithms within the STL
Theheader file contains
Non-modifying sequence operations
Do some calculation but dont change sequence itself
Examples include count, count_if
Mutating sequence operations
Modify the order or values of the sequence elements
Examples include copy, random_shuffle
Sorting and related operations
Modify the order in which elements appear in a sequence
Examples include sort, next_permutation
Theheader file contains General numeric operations
Scalar and matrix algebra, especially used with vector
Examples include accumulate, inner_product
8/13/2019 17A C Algorithms.ppt
11/16CSE 332: C++STL algorithms
Example of Using Non-Modifying Algorithms countalgorithm
Moves throughiterator range
Checks eachposition forequality
Increasescount if equal
#include #include #include
using namespace std;
int main (int, char * []){ vector v; v.push_back(1); v.push_back(2);
v.push_back(3); v.push_back(2);
int i = 7; cout
8/13/2019 17A C Algorithms.ppt
12/16
8/13/2019 17A C Algorithms.ppt
13/16
CSE 332: C++STL algorithms
Example of Using Mutating Algorithms copyalgorithm
Copies from an input iteratorrange into an output iterator
Note use of default constructorto get an off-the-end(here,end-of-file) input iterator
Note use of noskipws(ensurebehavior matchesexpectations)
input_file >> noskipws;
istream_iterator inF(input_file);
ostream_iterator otF(output_file);
copy (inF, istream_iterator(), otF);
cout
8/13/2019 17A C Algorithms.ppt
14/16
CSE 332: C++STL algorithms
Example of Using Sorting Algorithms sortalgorithm
Reorders a given range
Can also plug in afunctor to change theordering function
next_permutationalgorithm Generates a specific
kind of reordering,called a permutation
Can use to generate allpossible orders of agiven sequence
#include #include #include
using namespace std;
int main (int, char * []) {
string s = "asdf"; cout
8/13/2019 17A C Algorithms.ppt
15/16
CSE 332: C++STL algorithms
Example of Using Numeric Algorithms accumulate
algorithm Sums up elements in
a range (based on a
starting sum value) inner_product
algorithm Computes the inner
(also known as dot)product of two
vectors: sum of theproducts of theirrespective elements
#include #include #include
using namespace std;
int main (int, char * []) {
vector v; v.push_back(1); v.push_back(2); v.push_back(3);
v.push_back(2);
cout
8/13/2019 17A C Algorithms.ppt
16/16
CSE 332: C++STL algorithms
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
Reusing them saves you from writing code
Many STL algorithms can be extended
Especially by plugging function objects into them
Weve looked at how to use a few function objects
Next lecture well look at how function objects work
You can also create your own generic algorithms If something you need is not in the STL
Think about the iterator and data type concept it requires
Implement it so it works as generically as possible