list.sort()

Hey folks, I have a problem regarding using std::list::sort. I wrote my own comparator function below, and called sort with said function as the input parameter. I don't understand why the compiler cannot find the function when it seems to me that nothing's wrong. Help would be appreciated. Thanks.

#include<iostream>
#include<fstream>
#include<cmath>
#include<list>

class Driver
{
list<Point2D> Vp2d;
string filter, sortCriteria, sortOrder;
void doSort();

template <class line>
bool compareLength(line, line);

template <class point>
bool compareDist(point, point);

public: Driver();
};

void Driver::doSort()
{
if(filter=="Point2D")
{
if(sortCriteria=="Length")
Vp2d.sort(compareDist);
}
}

template <class point>
bool Driver::compareDist(point first, point second)
{
if(sortOrder=="ASC")
{
if(first.getScalarValue()<second.getScalarValue())
return true;

else
return false;
}

else if(sortOrder=="DSC")
{
if(first.getScalarValue()>second.getScalarValue())
return true;

else
return false;
}
}

Your Driver::compareDist<> is a member function (template). Member functions cannot be used with algorithms.

Your best bet is to make it a function object that takes sortOrder as a constructor argument (or, alternatively, use bind() to convert your existing member function to such object)
Heh, I guess putting this in the beginners subforum was the right place after all. I took a look at the documentation for functors(never used them before, haven't been taught anything about them yet) online but I'm not quite sure how to use them in this case. Could you kindly provide an example?
In this case, you could write something like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct CompareDist {
    std::string m_SortOrder;

    CompareDist(const std::string SortOrder) : m_SortOrder(SortOrder) {}

    template <class point>
    bool operator()(const point& first, const point& second) const
    {
        if(m_SortOrder=="ASC")
            return first.getScalarValue() < second.getScalarValue();
        else if(m_SortOrder=="DSC")
            return first.getScalarValue()>second.getScalarValue();
        else
            throw std::runtime_error("Unknown sort order " + m_SortOrder);
    }
};

and call it with

1
2
3
4
void Driver::doSort()
{
        Vp2d.sort( CompareDist(sortOrder) );
}


Topic archived. No new replies allowed.