Tuesday, March 25, 2008

STL: find in a list of pointers

Most STL tutorials will not help you solve this problem:
How to search in a list of pointers?
e.g vector<'obj*'>myList;
The find alogrithm on this will match only the pointer address and if you do not share your objects between classes then your find will always fail as it matches only the pointer addresses and not the value to which it points.
To fix this problem, the solutions that can be considered are:
1. store objects instead of pointers in the list. (huge memory overhead!!)
2. use find_if instead of find and write a functor which compares value instead of pointer address
3. Overload find and implement your own comparator in it. This comparator again compares the value instead of pointer address.

No comments: