How to define and use a custom comparison function

belkin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jun 15 16:22:18 PDT 2014


I am new to D so I am probably not using the right terminology 
but here is a piece of C++ code (not complete) that I would like 
to translate to idiomatic D.
I have defined a function object that I pass to std::sort to 
std:map as follows:

enum class SortOrder{ ASC, DESC };
typedef std::vector<boost::variant> DataRow; // this is one row 
of data in a 2D array. Data items are variants but this is not 
very important
typedef std::vector<DataRow> Data; // this is simply a 2D array
Data the_data;
// the function object is here. I don't want a lamda because I 
want to be able to call this from multiple places
class MyCompare
{
public:
	explicit MyCompare(int column, SortOrder order) : 
m_column(column), m_order(order) {}
	bool operator()(const DataRow& lhs, const DataRow& rhs)
	{
		switch (m_order)
		{
		case SortOrder::ASC:
			return lhs[m_column] < rhs[m_column];
		case SortOrder::DESC:
			return rhs[m_column] < lhs[m_column];
		}
	}
private:
	int m_column;
	SortOrder m_order;
};

example 1:
int column = 3;
SortOrder order = DESC;
std::sort(the_data.begin(), the_data.end(), MyCompare(column, 
order));

example 2:
MyCompare comp(column, order);
std::map<DataRow, Data, MyCompare> mp( comp );

What is the equivalent idiomatic D?


More information about the Digitalmars-d-learn mailing list