-3

I have a vector array of type Element. How can I now sort the array in Ascending order, based on the distance of each Element's Center value from 100?

In this case the resulting Elements vector array would result in the vector array being sorted something like this...

Elements sorted:

Elements.push_back(Element(77));
Elements.push_back(Element(128));
Elements.push_back(Element(20));
Elements.push_back(Element(-370));
Elements.push_back(Element(-489));

code:

#include "stdafx.h"
#include <iostream>
#include <vector>

using namespace std;


class Element
{
    public:
        int Center;

        Element(int center)
        {
            Center = center;
        }
};

int main(int)
{
    cout << "Start...\n";
    vector<Element> Elements;

    // add test objects
    Elements.push_back(Element(20));
    Elements.push_back(Element(-370));
    Elements.push_back(Element(128));
    Elements.push_back(Element(77));
    Elements.push_back(Element(-489));
    //cout << "value of a: " << Elements.size() << endl;

    for (vector<Element>::size_type i = 0; i != Elements.size(); i++) {
        cout << "value of a: " << Elements[i].Center << endl;
    }

    return 0;
}
JokerMartini
  • 5,674
  • 9
  • 83
  • 193

2 Answers2

3

Here is an example from here:

// sort using a lambda expression 
    std::sort(s.begin(), s.end(), [](int a, int b) {
        return b < a;   
    });

You provide a lambda that gives the logic about what criteria you are sorting with. In your case, the criteria will handle the Center variable. a and b are any two elements in your vector that are being compared.

In your case, yours will look something like this (I'm not at a compiler at the moment to test, and the specifics of your sort logic may be different than I understand):

std::sort(Elements.begin(), Elements.end(), [](Element a, Element b) {
     return abs(100 - b.Center) > abs(100 - a.Center);   
});
JokerMartini
  • 5,674
  • 9
  • 83
  • 193
johnbakers
  • 24,158
  • 24
  • 130
  • 258
0

Considering the fact that your example is wrong (77 should come before 128) you might want to use std::sort like this:

std::sort(Elements.begin(), Elements.end(), [](const Element& a, const Element& b) {
     return std::abs(100 - a.Center) < std::abs(100 - b.Center);   
});

The problem here is that if you were to have: 75 and 125 it will put 75 first (if that was inserted first), as pointed out by James Adkison.

Live example

Floris Velleman
  • 4,848
  • 4
  • 29
  • 46