Quote:Original post by WindScar
No, I don't want a function like "comparex", because that would require writing new "compare" functions everytime I store a new kind of object in the vector, or there's a new kind of variable I want to sort from. I just want the vector class totally independent from the type of object I want it to store. Passing the function pointer gives me that. Not CompareX, yes Compare(T::getx). Is that possible?
Assuming your compare function is simple and does something like < sometimes, > other times, etc, you can just make it a template function:
template<class T>bool is_less(const T& t1, const T& t2) { return t1 < t2; }
As long as t1 and t2 have the appropriate operator, it works. Anyway if you really want to use an arbitrary function pointer, you can use boost::bind
class Bar{};class Foo{public: bool do_compare(const Bar& b1, const Bar& b2) const { }};int main(int argc, char** argv){ std::vector<Bar> v; Foo comparer; std::sort(v.begin(), v.end(), boost::bind(&Foo::compare, &comparer, _1, _2));}
If you're using either Visual Studio 2010 Release Candidate or GCC 4.5, you can use C++0x lambdas.
std::vector<Bar> v; std::sort(v.begin(), v.end(), [](const Bar& b1, const Bar& b2) { b1.x < b2.x; } );