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

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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.
Last edited on
1
2
3
4
5
6
7
8
if (lhs[m_column] == rhs[m_column])
  {
    return lhs[m_column2] < rhs[m_column2];
  }   
else
  {   
    return lhs[m_column] > rhs[m_column];
  }

Is equivalent to:
1
2
3
4
5
6
7
8
if (lhs[m_column] != rhs[m_column])
  {   
    return lhs[m_column] > rhs[m_column];
  }
else
  {
    return lhs[m_column2] < rhs[m_column2];
  }

Or in other words:

Find the first column that is not identical, and return its relation.
Remember to handle the "entries are identical" too.
Topic archived. No new replies allowed.