Using a functor to sort a vector

In this example, we want array t to be in the same relative order of array v. The idea is to sort t and build an array of indexes (from 0 to n-1). Now, we sort the index array in the same order of array v, and then map array t using the index array.

#include <algorithm>
#include <stdio.h>

using namespace std;

class sort_class{

    int *v_;

    sort_class(int *v){
        v_ = v;
    bool operator() (int i, int j){
        return (v_[i] < v_[j]);

void print(int *v){
    for(int i=0; i<5; i++)
        printf("%d ", v[i]);

int main (){

    int v[] = {10, 30, 20, 50, 40};
    int t[] = {15, 27, 56, 12, 11};


    sort(t, t+5);

    int aux[] = {0, 1, 2, 3, 4};   

    sort_class s(v);
    sort(aux, aux+5, s);

    int tmp[5];
    for(int i=0; i<5; i++)
        tmp[i] = t[aux[i]];
    for(int i=0; i<5; i++)
        t[i] = tmp[i];


    return 0;

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s