sort multidimensional vector of ints?

后端 未结 2 1725
遇见更好的自我
遇见更好的自我 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<Table> 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 <algorithm>
    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;});
    
    0 讨论(0)
  • 2020-12-29 01:02
    std::sort(myVector.begin(), myVector.end(), [](const std::vector< int >& a, const std::vector< int >& b){ 
        //If you want to sort in ascending order, then substitute > with <
        return a[1] > b[1]; 
    }); 
    

    Please notice that you will need a C++11 compiler to get this code compile. You should make the lambda function accept const references to avoid expensive copies, as suggested by Blastfurnace.

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    int main(){
        std::vector< std::vector< int > > myVector({{3,4,3},{2,5,2},{1,6,1}});
        std::sort(myVector.begin(), myVector.end(), [](const std::vector< int >& a, const std::vector< int >& b){ return a[1] > b[1]; } );
    
        std::cout << "{";
        for(auto i : myVector){
            std::cout << "[";
            for(auto j : i)
                std::cout << j << ",";
            std::cout << "],";
        }
        std::cout << "}" << std::endl;
        return 0;
    }
    

    Output of the program:

    {[1,6,1,],[2,5,2,],[3,4,3,],}
    
    0 讨论(0)
提交回复
热议问题