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?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • What compiler and compiler version are you using? I did a simple console application using Visual Studio 2005 and this construct compiled and worked fine with the `std::vector` sorting. According to [Visual Studio support for new C/C++ standards?](http://stackoverflow.com/questions/146381/visual-studio-support-for-new-c-c-standards) and [Which standard does VS2005, VS2008 follow?](http://stackoverflow.com/questions/6211926/which-standard-does-vs2005-vs2008-follow) VS 2005 targets C++03. – Richard Chambers Oct 13 '15 at 17:47

2 Answers2

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;
}
NaCl
  • 2,683
  • 2
  • 23
  • 37
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.

Community
  • 1
  • 1
lrineau
  • 6,036
  • 3
  • 34
  • 47