sort multidimensional vector of ints?

2019-02-05 08:17发布

问题:

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"?

Many thanks in advance!

C++

res = mysql_perform_query(conn, "SELECT column1, column2, column3 FROM table1;");
std::vector< std::vector< int > > myVector;
while ((row = mysql_fetch_row(res)) !=NULL){
    int rankedID = atoi(row[0]);
    std::vector< int > tempRow;
    tempRow.push_back(atoi(row[0]));
    tempRow.push_back(atoi(row[1]));
    tempRow.push_back(atoi(row[2]));
    myVector.push_back(tempRow);
}

I'd like to sort myVector by myVector[i][1] descending.

Thanks again!

回答1:

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,],}


回答2:

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