排序int的多维向量? [英] sort multidimensional vector of ints?
问题描述
相信或不,当我搜索这个,我想出了nada。
如何排序多维向量$
提前感谢!
p>C ++
res = mysql_perform_query ,SELECT column1,column2,column3 FROM table1;);
std :: vector< std :: vector& int> > myVector;
while((row = mysql_fetch_row(res))!= NULL){
int sortedID = 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]
降序。
std :: sort(myVector.begin(),myVector.end(),[](const std :: vector< int>& a,const std :: vector< int& 1]> b [1];}); //如果要按升序排序,请替换>与<
我有眼睛的代码。我还没有尝试过。
请注意,您将需要一个c ++ 11编译器来获取此代码。
编辑:语法错误修复。
编辑:测试。有用。这里是测试的代码:
#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;
}
程序输出:
$ b b
{[1,6,1,],[2,5,2,],[3,4,3,],}
编辑:根据Blastfurnace的建议更改lambda函数接受const引用
Believe it or not, when I search this, I come up with nada.
How can I sort a multidimensional vector
of int
s by one of the "columns"?
Many thanks 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'd like to sort myVector
by myVector[i][1]
descending.
Thanks again!
Is this what you want?
std::sort(myVector.begin(), myVector.end(), [](const std::vector< int >& a, const std::vector< int >& b){ return a[1] > b[1]; } ); //If you want to sort in ascending order, then substitute > with <.
I have eyesballed the code. I haven't tried it yet. Please notice that you will need a c++11 compiler to get this code compile.
EDIT: syntax error fixed.
EDIT: tested. It works. here is the code for the test:
#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;
}
Output of the program:
{[1,6,1,],[2,5,2,],[3,4,3,],}
EDIT: changed the lambda function to accept const reference upon the suggestion of Blastfurnace
这篇关于排序int的多维向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!