I have
vector<vector<int>> vec
in my c++ app.
Every vector of integers as an element of "big" vector has 4 INT values.
I want to sort vec basing on third value of it's content vectors of ints (I mean every "inside" vector third element) - is it possible?
EDIT
Let's say I've got a function
COST(vector<int>)
which calculates me some value based on my vector values - can I use it in comparation parameter too? It'd help me a lot more.
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:
- The above works with C++98, too, I'm not sure about how widespread the use of C++11 is and whether you have a compliant compiler. Otherwise, you can of course use a lambda expression, too, as sftrabbit suggested.
- You don't say what COST returns, I simply assumed some sortable value like float or long.
- I hope you don't copy the vector when passing it to COST(), that would be horribly inefficient.
- COST suggests a macro, like all UPPERCASE_NAMES. Don't use macros. Don't use macro names for functions.
#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/