I have written code for a sort on a 2D vector depends on two columns. For example, If this is the data of 2D column
banana bike 2 | apple car 1 | orange cycle 5 | banana car 2 | apple bike 3
Then my sort will change this data as,
apple bike 3 | apple car 1 | banana bike 2 | banana car 2 | orange cycle 5
I have given below my Coding.
class StringListCompare
{
public:
explicit StringListCompare(int column, int column2) : m_column(column), m_column2(column2) {}
bool operator()(const vector<string>& lhs, const vector<string>& rhs)
{
if (lhs[m_column] == rhs[m_column])
{
return lhs[m_column2] < rhs[m_column2];
}
else
{
return lhs[m_column] > rhs[m_column];
}
}
private:
int m_column;
int m_column2;
};
Now I want to extend this 2 column level sort to unlimited column level sort. So I changed this code as given below. But I don't What logic I missing here.
class CompareSort
{
public:
explicit CompareSort(std::vector<int> fcol,string fsortTyp,string fcaseflg): colNums(fcol) , sortTyp(fsortTyp), caseflg(fcaseflg) {}
bool operator()(const vector<string>& lhs, const vector<string>& rhs)
{
int ret;
size_t noCol=colNums.size();
for(size_t i=0;i<noCol;i++)
{
string lhStr=lhs[colNums[i]];
string rhStr=rhs[colNums[i]];
if(caseflg=="n")
{
lowercase(lhStr);
lowercase(rhStr);
}
if(sortTyp=="asc")
ret= lhStr < rhStr;
else
ret= lhStr > rhStr;
}
return ret;
}
private:
std::vector<int> colNums;
string sortTyp,caseflg;
};
How do i check this line
if (lhs[m_column] == rhs[m_column])
in my second program.
Here's some pseudocode that might help you a bit:
bool compare(lhs, rhs) {
//compare lhs and rhs, which you know is different at this point
}
bool operator()(lhs, rhs) {
for i := 0 to noCol
if lhs[i] != rhs[i]
return compare(lhs, rhs)
//We know now that lhs and rhs are equal
return true;
}