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;
}