5

信不信由你,当我搜索这个时,我想出了 nada。

如何按“列”之一对 svector的多维进行排序?int

提前谢谢了!

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

我想myVectormyVector[i][1]降序排序。

再次感谢!

4

2 回答 2

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

请注意,您将需要 C++11 编译器来编译此代码。正如 Blastfurnace 所建议的,您应该使 lambda 函数接受 const 引用以避免昂贵的副本。

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

程序的输出:

{[1,6,1,],[2,5,2,],[3,4,3,],}
于 2013-02-03T05:20:40.400 回答
4

我的建议是使用结构表虽然:

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

如果您使用 C++11,也可以使用 lambda:

std::sort(myVector.begin(), myVector.end(), 
         [](const Table& lhs, const Table& rhs){return lhs.column2 < rhs.column2;});
于 2013-02-03T05:19:11.757 回答