Noeud:find, Noeud « Next »:transform, Noeud « Previous »:for_each, Noeud « Up »:Generic Algorithms and Function Objects
Now that you've had a brief taster with for_each, everything get's a
little easier. Understanding the signature of different algorithms becomes
instinctively easier the more you use them. find has the following
signature:
InputIterator find(InputIterator begin, InputIterator end,
const T& val)
It's very straight forward: supply some start and end range, a value to search
for, and return the position of where the element was, (find returns
end() if the element was not found). There is also another algorithm
called find_if that uses some operation to perform a test on the
element being searched for:
InputIterator find_if(InputIterator begin, InputIterator end,
UnaryPredicate op)
Let's look at find:
/* generic2.cc
* Compiled using g++ generic2.cc Address.cc -o generic2
* Run using ./generic2 */
#include <algorithm>
#include <list>
#include "AddressRepository.hh"
int main()
{
list<Address> l;
l.push_front(addr1);
l.push_front(addr2);
l.push_front(addr3);
l.push_front(addr4);
l.push_front(addr5);
Address addr6("Jane", "55 Almond Terrace", "Worcs", 242783);
list<Address>::iterator pos = find(l.begin(), l.end(), addr6);
if (pos != l.end())
{
cout << "Found : ";
pos->print();
}
return 0;
}
Example 3.20: generic2.cc
Once again, the example is easy to follow: we just supply the populated list
to the find algorithm using begin() and end() and specify
that we want to find a match with addr6. Note that since we test only
for the name of an Address object, any Address object with
the name "Jane" would have satisfied the search.
What about find_if? It's pretty straight forward really, and involves
using bind2nd():
/* generic3.cc
* Compiled using g++ generic3.cc Address.cc -o generic3
* Run using ./generic3 */
#include <algorithm>
#include <functional>
#include <list>
#include "AddressRepository.hh"
int main()
{
list<Address> l;
l.push_front(addr1);
l.push_front(addr2);
l.push_front(addr3);
l.push_front(addr4);
l.push_front(addr5);
Address addr6("Jane", "55 Almond Terrace", "Worcs", 242783);
list<Address>::iterator pos = find_if(l.begin(), l.end(),
bind2nd(less<Address>(), addr6));
if (pos != l.end())
{
cout << "Found : ";
pos->print();
}
return 0;
}
Example 3.21: generic3.cc
The code is almost the same as the previous example using find(),
except this time we need a unary predicate as the third argument to
find_if(). We achieve this by saying that we want to find any
Address object less than addr6, in other words any
Address object less than "Jane". Since "Bob" is the first
element we'll encounter and is less than "Jane" according to our
less-than sorting criterion, pos is assigned to the iterator that
points to "Bob".