在2D矢量C 中超过两个列排序

More than two column sort in 2d vector c++

本文关键字:两个 排序 矢量 2D 中超      更新时间:2023-10-16

我已经为2D向量上的一种编写代码取决于两列。例如,如果这是2D列的数据

香蕉自行车2 |苹果汽车1 |橙色周期5 |香蕉车2 |苹果 自行车3

然后我的排序将将此数据更改为

苹果自行车3 |苹果汽车1 |香蕉自行车2 |香蕉车2 |橙子 周期5

我在我的编码下给出了。

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;
};

现在,我想将此2列级排序扩展到无限的列级排序。因此,我更改了此代码,如下所示。但是我不在这里缺少什么逻辑。

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;
};

我如何检查此行

if (lhs[m_column] == rhs[m_column])

在我的第二个程序中。

以下是一些可能对您有所帮助的伪代码:

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;
}