5

信じられないかもしれませんが、これを検索すると nada が出てきます。

「列」の1つでsの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]

再度、感謝します!

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 で提案されているように、高価なコピーを避けるために、ラムダ関数が 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;  
};

DB からの各行を構造体に入れ、ベクターに格納します。

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 を使用している場合は、ラムダも使用できます。

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