【问题标题】:More than two column sort in 2d vector c++二维向量c ++中的多于两列排序
【发布时间】:2014-02-12 14:25:49
【问题描述】:

我已经编写了代码,用于对 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])

在我的第二个程序中。

【问题讨论】:

    标签: c++ sorting std multiple-columns 2d-vector


    【解决方案1】:

    这里有一些伪代码可能会对你有所帮助:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-16
      • 2018-01-11
      • 1970-01-01
      相关资源
      最近更新 更多