Quote:Original post by d000hg I was going to try a binary heap or the lower_bound functions, but the container contains pointers to objects. How can I get the ordering comaprisions to be made on the object pointed to, not based on the pointer's value? |
std::lower_bound and the heap operations are overloaded to take a binary predicate this means you can use any C++ callable entity with it, you can use a free/member function or functor e.g.:
1. using free-function:
#include <algorithm>#include <vector>struct foo { //......};bool foo_compare(const foo* lhs, const foo* rhs) { //......}//.....typedef std::vector<foo*> foo_vec;foo_vec l;//....foo* new_val = //.....foo_vec::iterator result = std::lower_bound(l.begin(), l.end(), new_val, foo_compare);// ...std::make_heap(l.begin(), l.end(), foo_compare);
2. using a member function:
#include <algorithm>#include <functional> // mem_fun#include <vector>struct foo { //.... bool compare(const foo* f) const { /* ... */ }};typedef std::vector<foo*> foo_vec;foo_vec l;//....foo* new_val = //.....foo_vec::iterator result = std::lower_bound(l.begin(), l.end(), new_val, std::mem_fun(&foo::compare));std::make_heap(l.begin(), l.end(), std::mem_fun(&foo::compare));
3. using a functor:
#include <algorithm>#include <vector>struct foo { //......};struct foo_compare { bool operator()(const foo* lhs, const foo* rhs) const { /* ... */ }};//.....typedef std::vector<foo*> foo_vec;foo_vec l;//....foo* new_val = //.....foo_vec::iterator result = std::lower_bound(l.begin(), l.end(), new_val, foo_compare());// ...std::make_heap(l.begin(), l.end(), foo_compare());
[Edited by - snk_kid on September 28, 2005 4:43:33 AM]