Thursday, September 18, 2008

Sorting by a different comparison method in C++ (STL)

You have a list of numbers in C++ that you want to sort, but you don't want to sort them in simple numerical order. You might, for example, want to sort them by their deviation from 0. Here's how you do it using the STL:

#include <vector>
#include <iostream>

using namespace std;

class compare_deviation
{
public:
compare_deviation(int d) : deviation(d) {
}

bool operator ()(const int p1,const int p2)
{

int v1 = abs(deviation - p1);
int v2 = abs(deviation - p2);
return(v1 < v2);
}

int deviation;
};


int main() {


vector<int> numbers;

numbers.push_back(1);
numbers.push_back(-10);
numbers.push_back(-9);
numbers.push_back(-5);
numbers.push_back(0);
numbers.push_back(5);
numbers.push_back(6);
numbers.push_back(7);
numbers.push_back(10);
numbers.push_back(11);

compare_deviation comp(0);

cout << "Unsorted numbers: ";

for(vector<int>::iterator i=numbers.begin();i != numbers.end();i++) cout << " " << (*i);
sort(numbers.begin(),numbers.end(),comp);
cout << endl;

cout << "Sorted numbers: ";
for(vector<int>::iterator i=numbers.begin();i != numbers.end();i++) cout << " " << (*i);
cout << endl;

return 1;
}



Bang On!

No comments: