sorting vector of vector of strings in C++

后端 未结 4 585
既然无缘
既然无缘 2020-12-21 01:23

I am having trouble to figure out, how to sort a vector of vector of strings, here is the testing code.


#include <iostream>
#include <vector>
#incl         


        
4条回答
  •  执念已碎
    2020-12-21 01:43

    If you only want to sort based on the second column, then you just need to provide a custom comparison operator. Once way to do that is:

    struct StringListCompare
    {
      bool operator()(const vector& lhs, const vector& rhs)
      {
        // what do we do if lhs or rhs don't have two elements?
        if (lhs.size() < 2 || rhs.size() < 2)
        {
          // ?
        }
        else
        {
          return lhs[1] < rhs[1];
        }
      }
    } StringListComparer;
    
    int main()
    {
      // ...
      sort(data_var.begin(), data_var.end(), StringListComparer);
    }
    

    Edit: If you won't know until runtime which column you'll be sorting on, you can encode that in the sorting object:

    class StringListCompare
    {
    public:
      explicit StringListCompare(int column) : m_column(column) {}
      bool operator()(const vector& lhs, const vector& rhs)
      {
        // what do we do if lhs or rhs don't have (m_column + 1) elements?
        return lhs[m_column] < rhs[m_column];
      }
    private:
      int m_column;
    };
    

    Notice how we've added a constructor that takes which column it'll act on. You can use it like this:

      // We set it up so the columns are 0-based:
      StringListCompare compare_column_0(0), compare_column_1(1), compare_column_2(2);
    
      cout << "Original:\n" << data_var << endl;
      sort(data_var.begin(), data_var.end(), compare_column_2);
      cout << "Sorted on column 2:\n" << data_var << endl;
      sort(data_var.begin(), data_var.end(), compare_column_1);
      cout << "Sorted on column 1:\n" << data_var << endl;
      sort(data_var.begin(), data_var.end(), compare_column_0);
      cout << "Sorted on column 0:\n" << data_var << endl;
    

    You don't even need to make the local variable if you don't want to:

      sort(data_var.begin(), data_var.end(), StringListCompare(2));
      cout << "Sorted on 2, no local sort variable:\n" << data_var << endl;
    

    [Code at ideone]

提交回复
热议问题