sort multidimensional vector of ints?

后端 未结 2 1726
遇见更好的自我
遇见更好的自我 2020-12-29 00:29

Believe it or not, when I search this, I come up with nada.

How can I sort a multidimensional vector of ints by one of the \"columns\"?

2条回答
  •  既然无缘
    2020-12-29 00:43

    My suggestion is use struct for table though:

    struct Table
    {
      Table(int c1, int c2, int c3)
      : column1(c1),
        column2(c2),
        column3(c3)
      {
      }
    
      int column1;
      int column2;
      int column3;  
    };
    

    Put each row from DB into a struct then store it in vector:

    std::vector myVector;
    while ((row = mysql_fetch_row(res)) !=NULL)
    {
        myVector.push_back(Table(atoi(row[0]), atoi(row[1]), atoi(row[2]));
    }
    

    Now you could sort vector by any column

    #include 
    struct 
    {
        bool operator()(const Table& lhs, const Table& rhs)
        {   
          return lhs.column2 > rhs.column2;
        }   
    } ColumnLess;
    
    std::sort(myVector.begin(), myVector.end(), ColumnLess);
    

    If you use C++11, could use lambda as well:

    std::sort(myVector.begin(), myVector.end(), 
             [](const Table& lhs, const Table& rhs){return lhs.column2 < rhs.column2;});
    

    提交回复
    热议问题