整数多维向量的整数?

时间:2013-02-03 04:36:45

标签: c++ sorting vector int multidimensional-array

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

如何通过其中一个“列”对多维vector 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);
}

我想按myVector降序排序myVector[i][1]

再次感谢!

2 个答案:

答案 0 :(得分: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编译器来编译此代码。您应该使lambda函数接受const引用以避免昂贵的副本,如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;
}

计划的输出:

{[1,6,1,],[2,5,2,],[3,4,3,],}

答案 1 :(得分:4)

我的建议是使用struct for table:

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

  int column1;
  int column2;
  int column3;  
};

将DB中的每一行放入一个struct中,然后将其存储在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]));
}

现在您可以按任意列对矢量进行排序

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