Sort multidimensional vector ints?

Believe it or not, when I look for it, I come up with nadu.

How can I sort multidimensional vectorfrom intone of the columns?

Thank you very much 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 would like to sort myVectorby myVector[i][1]descending order.

Thanks again!

+5
source share
2 answers
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]; 
}); 

Note that to compile this code, you will need a C ++ 11 compiler. You must have the lambda function accept constant links in order to avoid expensive copies, as Blastfurnace suggests.

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

Program Output:

{[1,6,1,],[2,5,2,],[3,4,3,],}
+8
source

My suggestion is to use struct for table:

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

  int column1;
  int column2;
  int column3;  
};

, :

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

#include <algorithm>
struct 
{
    bool operator()(const Table& lhs, const Table& rhs)
    {   
      return lhs.column2 > rhs.column2;
    }   
} ColumnLess;

std::sort(myVector.begin(), myVector.end(), ColumnLess);

++ 11, :

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

All Articles