2

This may be a silly question, but I wrote a code like below.

void someFunction() { struct sort_pred { inline bool operator()(const std::pair<int,double> &left, const std::pair<int,double> &right) const { return left.second < right.second; } }; std::sort(regionAreas.begin(), regionAreas.end(), sort_pred()); } 

However, this doesn't compile saying,

///:1542: error: no matching function for call to 'sort(std::vector<std::pair<int, double> >::iterator, std::vector<std::pair<int, double> >::iterator, someFunction::sort_pred)' 

How could I use a struct inside a function as a comparator? Or, is it impossible?

1

2 Answers 2

0

This is a good example of using a wrapper. Even if we would implement a conversion from sort_pred to std::pair<int, double>, it wouldn't work as well, because std::pair<int, double> has no operator(). So storing the wrapper instead of std::pair<int, double> will do a good job.

class sort_pred; class wrapper { public: //some conversion-stuff from std::pair<int, double> to wrapper //not really needed in this example wrapper(const std::pair<int, double>& p) : _p(p) {} //needed in operator wrapper() in sort_pred wrapper(const sort_pred *s) : _p() { ////// //maybe you want access to private-members of //sort_pred in here, so just add friend class sort_pred //to the class, if this is the case. ////// //Just let the magic happen ////// } //for std::sort bool operator()(const wrapper &left, const wrapper &right) { return left._p.second < right._p.second; } private: std::pair<int, double> _p; }; struct sort_pred { sort_pred(){} //This allows us to static_cast sort_pred to wrapper operator wrapper() { return wrapper(this); } }; bar foo() { std::vector<wrapper> regionAreas; //some stuff with regionAreas.push_back :D std::sort(regionAreas.begin(), regionAreas.end(), static_cast<wrapper>(sort_pred())); return bar_value; } 
Sign up to request clarification or add additional context in comments.

Comments

0

Your question seems a duplicate of Using local classes with STL algorithms.

In short, that is allowed in C++11, but not by previous versions of the C++ norm.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.