Gambit King
Gambit King

Reputation: 483

Sorting Multidimensional array/vector

I want to sort the array based on two values that are stored in elements sequ[i][2] and sequ[i][3].

If sequ[i][2] has similar values, it sorts it by sequ[i][3] value.

vector< vector<int> > sequ;
int m = 1024, n = 32;
sequ.resize(m);
for(int i = 0 ; i < m ; ++i){
sequ[i].resize(n);
}
sort(sequ[0].begin(),sequ[0].end());

Unfortuantely i know only how to sort the array as a whole but not specific elements. How do i do this

Upvotes: 0

Views: 1050

Answers (2)

JasonD
JasonD

Reputation: 16582

The non-lambda method of doing this would be something like:

bool func(const vector<int> &v1, const vector<int> &v2)
{
    if(v1[2] < v2[2]) return true;
    if(v1[2] > v2[2]) return false;
    return v1[3] < v2[3];
}

...

sort(sequ.begin(),sequ.end(),func);

Upvotes: 2

Alexander Chertov
Alexander Chertov

Reputation: 2108

If you had C++11 you should try something along these lines.

sort(  secu.begin(), secu.end(), [](const vector<int>&v1, const vector<int>&v2) -> bool
{
  return v1[2] < v2[2] || (v1[2] == v2[2] && (v1[3] < v2[3]) );
});

I'm not a super pro in C++11 lambda syntax, but you should get the idea. If you don't have C++11 you can always roll out your own comparison functor.

Upvotes: 1

Related Questions