Searching for elements in a generic list

I'm trying to figure out how to perform a search when using templates. I'm writing my own version of <List>

Normally I would use something like this


1
2
3
4
5
6
7
element * List::find(int d)
{
    element *p;
    for(p = first; p && p->d != wanted; p = p->next)
        ;
    return p;
}


And so when writing this to a template version I would get this

1
2
3
4
5
6
7
8
template <class T>
element<T> * List<T>::find(T d)
{
    element *p;
    for(p = first; p && p->d != wanted; p = p->next)
        ;
    return p;
}



But what I would really want is to use find to search for an object using a single object member as a parameter, not an entire object. Like, if i had a class called Dog, and it had members such as int age, string name etc., and I wanted to use age to search for that dog in the list. Very thankful for any pointers on how to achieve this.

Use a comparator function
eg:
1
2
3
4
5
6
7
8
9
10
11
template < class T, class Compare >
... find ( ..., const Compare &cmp = std::equal_to<T>() )
{
    if ( cmp ( A, B ) )
        A and B are equal according to the comparator
}

bool equal_name ( Dog a, Dog b ) // function to use as comparator, pass it to find
{
    return a.name == b.name;
}
Last edited on
That works! Thanks!
Topic archived. No new replies allowed.