-1

I have a vector with 3 columns.

{0,1,10}
{0,2,15}
{0,3,33}
{0,4,12}

How can I get the next result ?

{0,3,33}
{0,2,15}
{0,4,12}
{0,1,10}

As I think I should use the following code:

std::sort(a.begin(), a.end(),
    [](const std::vector< int >& a, const std::vector< int >& b)
    { return a[1] > b[1]; });

So I need to sort according to the third number in each vector but first two should also go up because i need a list with sorted vector.

Synxis
  • 9,236
  • 2
  • 42
  • 64

2 Answers2

3

In your lambda used to compare elements of primary vector, you check second elements, not third. Also, you don't compare other values. So if you write textually what you want:

v1 is greater than v2:

  • if v1 third element is greater than v2 third element
  • or if v1 third element is equal than v2 third element and v1 second element is greater than v2 second element
  • of if 2 last element of v1 and v2 are equals and v1 first element is greater than v2 first element

Just translate it to c++:

http://coliru.stacked-crooked.com/a/44fff0423ff6ca6b

std::sort(a.begin(), a.end(),
    [](const std::vector< int >& a, const std::vector< int >& b)
        { 
            return a[2] > b[2]  // Note here 2 instead of 1
                || (a[2] == b[2] && a[1] > b[1])
                || (a[2] == b[2] && a[1] == b[1] && a[0] > b[0]); 
        });
Garf365
  • 3,619
  • 5
  • 29
  • 41
1

Yes, but, also you can use functional object like this. Lambas and functions working slower, than functional objects in this context. Functional object is the best solution

class my_compare_class
{
public:
    inline bool operator()(const std::vector< int > &a, const std::vector< int > &b)
    {
        // Third column is 2-nd index, because counting was started from 0
        return a[2] > b[2];
    }
};

Using std::sort(a.begin(),a.end(),my_compare_class());

EDIT: Added using example.

Inline
  • 2,566
  • 1
  • 16
  • 32
  • That would sort in the opposite direction as asked... – Aconcagua Jun 13 '16 at 09:51
  • @Aconcagua oops... – Inline Jun 13 '16 at 09:52
  • and using it as `std::sort(a.begin(),a.end(),my_compare_class());` – Gaurav Sehgal Jun 13 '16 at 10:09
  • Any link that shows why lambdas are slower than functors? Some say that lambdas are better because there is less code and the logic is at the place of the actual sorting. – stefaanv Jun 13 '16 at 10:20
  • @stefaanv About functions and lambdas perfomance: http://stackoverflow.com/questions/25520287/lambda-vs-function . Functors are faster because compiler always inlining operator() – Inline Jun 13 '16 at 10:22
  • thanks a lot , both answers are good and very helpful. Can't give that star both but the first answer is clearer. – Misha Ostapchuk Jun 13 '16 at 11:08
  • 1
    @Inline: note that the accepted answer on the 'already answered question' negates what you're saying (http://stackoverflow.com/a/13722515/104774), so let's call this undecided. – stefaanv Jun 13 '16 at 12:18