[英]More than two column sort in 2d vector c++
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
例如,如果这是2D列的数据
banana bike 2 |
香蕉车2 | apple car 1 |
苹果车1 | orange cycle 5 |
橙色周期5 | banana car 2 |
香蕉车2 | apple bike 3
苹果自行车3
Then my sort will change this data as, 然后我的排序将更改为
apple bike 3 |
苹果自行车3 | apple car 1 |
苹果车1 | banana bike 2 |
香蕉车2 | banana car 2 |
香蕉车2 | orange cycle 5
橙色周期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. 现在,我想将此2列级别的排序扩展为无限的列级别的排序。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.