整数多维向量的整数?

5 c++ sorting int vector multidimensional-array

信不信由你,当我搜索这个时,我想出了虚无...

我如何排序多维vectorint由"列"由一个s?

提前谢谢了!

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);
}
Run Code Online (Sandbox Code Playgroud)

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

再次感谢!

Kon*_*lex 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]; 
}); 
Run Code Online (Sandbox Code Playgroud)

请注意,您需要一个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;
}
Run Code Online (Sandbox Code Playgroud)

计划的输出:

{[1,6,1,],[2,5,2,],[3,4,3,],}
Run Code Online (Sandbox Code Playgroud)