I have
vector> vec
in my c++ app.
Every vector of integers as an element of \"big\" vector has 4 INT valu
Sure it is. std::sort
can take a third parameter which is the comparison function to use when sorting. For example, you could use a lambda function:
std::vector<std::vector<int>> vec;
// Fill it
std::sort(vec.begin(), vec.end(),
[](const std::vector<int>& a, const std::vector<int>& b) {
return a[2] < b[2];
});
Alternatively, you can pass anything else callable with signature bool(const std::vector<int>&, const std::vector<int>&)
, such as a functor or function pointer.
Response to edit: Simply apply your COST
function to a
and b
:
std::sort(vec.begin(), vec.end(),
[](const std::vector<int>& a, const std::vector<int>& b) {
return COST(a) < COST(b);
});
If you want to compare the two vectors by cost, try this:
bool predicate(const std::vector<int>& a, const std::vector<int>& b)
{
return COST(a) < COST(b);
}
Notes:
sort(vec.begin(), vec.end(), comp);
where comp
is:
static bool comp(const vector<int>& vec1, const vector<int>& vec2){
return vec1[2] < vec2[2];
}
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>
using namespace std;
// This makes the sort be according to column 2 and ascending
bool sortFunc( const vector<int>& p1,
const vector<int>& p2 ) {
return p1[1] < p2[1];
}
int main() {
srand(time(NULL));
// Creates and initializes 10 x 4 vector
vector< vector<int> > vec;
for( int i=0; i<10; i++ ) {
vector<int> tmpVec;
for( int j=0; j<2; j++ ) {
tmpVec.push_back( rand()%10 );
}
vec.push_back( tmpVec );
}
// Print out the pre-sorted vector
cout << "Pre-sorting state:" << endl;
for( int i=0; i<vec.size(); i++ ) {
for( int j=0; j<vec[i].size(); j++ ) {
cout << vec[i][j] << " ";
}
cout << endl;
}
cout << endl;
// Do the sorting according to column 2
sort(vec.begin(), vec.end(), sortFunc);
// Print out the post-sorted vector
cout << "Post-sorting state:" << endl;
for( int i=0; i<vec.size(); i++ ) {
for( int j=0; j<vec[i].size(); j++ ) {
cout << vec[i][j] << " ";
}
cout << endl;
}
return 0;
}
source: https://shihho.wordpress.com/2012/11/28/sort_with_vectors/