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\"?
My suggestion is use struct for table though:
struct Table
{
Table(int c1, int c2, int c3)
: column1(c1),
column2(c2),
column3(c3)
{
}
int column1;
int column2;
int column3;
};
Put each row from DB into a struct then store it in vector:
std::vector myVector;
while ((row = mysql_fetch_row(res)) !=NULL)
{
myVector.push_back(Table(atoi(row[0]), atoi(row[1]), atoi(row[2]));
}
Now you could sort vector by any column
#include
struct
{
bool operator()(const Table& lhs, const Table& rhs)
{
return lhs.column2 > rhs.column2;
}
} ColumnLess;
std::sort(myVector.begin(), myVector.end(), ColumnLess);
If you use C++11, could use lambda as well:
std::sort(myVector.begin(), myVector.end(),
[](const Table& lhs, const Table& rhs){return lhs.column2 < rhs.column2;});
- 热议问题