Sorting vector of arrays by array's element

2019-09-21 21:21发布

问题:

I have encountered a problem when writing algorithm for solving Knapsack problem. I have a vector of 3-element arrays (C++11) and I want to sort the vector by the value of let's say first element of these arrays.

I've tried std::sort with predefined compare function, but it doesn't even compile.

I guess my compare function doesn't work as I expect:

bool compareByValue(const data &a, const data &b)
{
    return a[0] < b[0];
}

int main()
{
    vector<array<int, 3> > myVector;
    ...
    sort ( myVector.begin(), myVector.end(), compareByValue );
}

It's not the first time when I have the similar problem, I tried to find solution on the Net, but without any satisfying result.

回答1:

I don't know where you got data from, but you need to change it to array<int, 3> or make compareByValue a template:

bool compareByValue(const array<int, 3> &a, const array<int, 3>&b)
{
    return a[0] < b[0];
}


回答2:

Also note that std::array has overloaded comparison operators, which compare arrays lexicographically. That means, if you want to sort based on the first element, you don't even need a predicate. Just std::sort your vector.