Reputation: 49
I'd like to sort an array of pointers, however VS won't compile, saying
'testClass::compareItems': non-standard syntax; use '&' to create a pointer to member
The comparer looks like this:
bool testClass::compareItems(ElementType *a, ElementType *b)
{
return elementToProfit[a] / a->w() > elementToProfit[b] / b->w();
}
while the array is just a normal array.
for (auto &knapsack : knapsacks)
{
std::sort(knapsack.second.begin(), knapsack.second.end(), compareItems);
}
I'm not quite sure what's going on. VS is also complaining that
'void std::sort(_RanIt,_RanIt)': expects 2 arguments - 3 provided
which I assume is because there's an issue with the comparer? This should be super easy... any help is greatly apprecitated, thanks!
Upvotes: 1
Views: 375
Reputation: 1
Two steps I found: (Assume knapsack.second
is vector)
bool opeator()(...){...}
;sort(knapsack.second.begin(), knapsack.second.end(),*this)
.Upvotes: 0
Reputation: 308346
The compare function can't be a non-static member of the class, since it isn't called on an instance of the class. It can be a static class function, a free-standing function, or a functor.
Judging by comments on the question, you may find a functor to be the best way forward. A functor is simply a class that implements operator()
so that you can use an object of it with function call syntax. The benefit of this approach is that the object can contain additional members that you need to carry along for the comparison.
typedef std::unordered_map<ElementType*, double> ProfitType;
class functorClass
{
ProfitType & elementToProfit;
public:
functorClass(ProfitType & pt) : elementToProfit(pt) {}
bool operator()(ElementType *a, ElementType *b)
{
return elementToProfit[a] / a->w() > elementToProfit[b] / b->w();
}
};
functorClass functor(elementToProfit);
for (auto &knapsack : knapsacks)
{
std::sort(knapsack.second.begin(), knapsack.second.end(), functor);
}
Upvotes: 4
Reputation: 43662
A member function has an extra argument (the this
pointer for the instance) therefore your signature isn't matching - the std::sort
needs to call the function without an object reference.
The documentation also states that it should satisfy the requirements of a binary predicate.
This is a sample reproducer
struct ElementType {
int w() {
return 2;
}
};
class testClass {
public:
bool compareItems(ElementType *a, ElementType *b)
{
return a->w() < b->w();
}
void sort() {
vector<ElementType*> vecOfPointers;
std::sort(vecOfPointers.begin(), vecOfPointers.end(), compareItems);
}
vector<ElementType*> elementToProfit;
};
You can fix your code by making your comparison function static
(example).
Your second error is a direct consequence of the first one. Fix the first and you'll solve the second as well.
Upvotes: 1