How to sort a 2D array by column

katuday via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 7 12:06:09 PDT 2014


I have a dynamic array of dynamic array of strings
I want to sort the outer array based on specific columns of the 
inner array

This is how I am populating the 2D array

void readFromFile()
{
	alias Row = string[];
	alias Table = Row[];
	
	Row the_row;
	Table the_table;
	
	auto inFile = File("sample.txt", "r");
	auto temp = chomp(inFile.readln()); // skip header
	while (!inFile.eof())
	{
		string row_in = chomp(inFile.readln());
		the_row = split(row_in,"\t");
		the_table ~= the_row;
	}
	writeln(the_table.length);
	the_table.sort; // I believe this sort uses all the columns 
inside the_row. What I want is use specific column(s)
}

This is my attemot to create a compare object. But I don't know 
how to use it together with .sort member function

class RowCompare
{
	int[] m_columns;
	
	this(int[] columns)
	{
		m_columns = m_columns;
	}
	
	int opCmp()(ref const Row lhs, ref const Row rhs) const
	{
		for (auto i = 0; i < m_columns.length; ++i)
		{
			ref const auto currentColumn = m_columns[i];
			if (lhs[currentColumn] < rhs[currentColumn] )
				return true;
			if (rhs[currentColumn] < lhs[currentColumn] )
				return false;
		}
	}
}


More information about the Digitalmars-d-learn mailing list