Vous êtes sur la page 1sur 13

10.1-10.

GENERIC
ALGORITHMS
10.1

 In general algorithms work by traversing a range of


elements
 As it moves, it does something to each element
 Example: the find algorithm

 If 42 is in vec, the program will cout “The value 42 is


present”
10.2
How Algorithms Work

The steps find must take:


1. Access the first element of the sequence
2. Compare the element to the value we want
3. If they match, return a value that identifies that
element
4. Otherwise advance to the next element and repeat
steps 2 and 3
5. Stop when it reaches the end of the sequence
6. If it gets to the end, return a value indicating the no
element was found
How Algorithms Work

Name (startingPoint, endingPoint, value)


 Algorithms operate over a range of elements
 Vectors, lists, arrays
 Specified start, specified end
 Do something with the element and the value
Kinds Of Algorithms

 Read algorithms
 Ex: find, count, accumulate

 Write algorithms
 Ex: fill

 Rearrange algorithms
 Ex: sort
10.2.1
Read Algorithms

 Example: accumulate

 Must be able to add element type to the type of the


sum
10.2.1
Read Algorithms on Two Sequences

 The equal algorithm


 Compares elements from the first sequence and
compares them to the corresponding element of the
second sequence
 Requires the second sequence to be at least as big as
the first sequence
10.2.2
Write Algorithms

 The sequence we are writing to must be at least as


large as the number of elements we ask the
algorithm to write
 Algorithms do not check write operations
 If we ask an algorithm to write past existing elements, results
in error
 Three examples: fill, fill_n, copy
The fill Algorithm

 Takes a pair of iterators that denote a range and a


third argument that is a value
The fill_n Algorithm

 Takes a single iterator, a count, and a value


 Starting at the iterator, replaces each element with
the value, count amount of times
The copy Algorithm

 Takes a pair of iterators that denote a range and a


third that denotes the beginning of a destination
sequence
 The destination must be at least as large as the input
range
10.2.3
Reorder Algorithms

 Example: sort
 Assume the vector words

The Quick Red fox Jumps Over The Slow Red turtle

 After applying

we are left with


Fox Jumps Over Quick Red Red Slow The The turtle
10.3.1
Predicates

 A predicate is an expression that can be called and


returns a value that can be used as a condition
 Some algorithms can use predicates as arguments

Vous aimerez peut-être aussi