Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Sorting Class Array

Tags:

c++

C++ Sorting Array Class

I have an array object that record the following..

This is at classone.h

ClassOne
{
string name;
int data;
float valueData;
}

and the constructor are created at classone.cpp

At main.cpp I created ClassOne Array of Size 10

#include "classone.h"

ClassOne cone[10];

Next is i recorded several value to the object

and now ClassOne got 3 objects

cone[0]
name = "hello"
data = 1
valueData = 20

cone[1]
name = "panda"
data = 2
valueData = 15

cone[2]
name = "joe"
data = 3
valueData = 25

What i want to achieve is do a sort that can rearrange this array by valueData highest ascending form so.. it will be

cone[2] then cone[0] then cone[1] ..

but the issue if i use bubble sort , i tried google and find some, they are sorting by e.g int a[]={9,6,5,23,2,6,2,7,1,8};

but i wanna sort by class array object. and re-arrange the value together , how do i achieve this.

So when i cout it will be

-- Highest to lowest --
1) Name: Joe , Data = 3, Value =25
2) Name: Hello , Data =1 , Value = 20
3) Name: Panda, Data = 2, Value = 15

Thanks for all help and guide!!

like image 450
baoky chen Avatar asked Oct 10 '12 15:10

baoky chen


1 Answers

The easiest way is to use the standard library:

#include <algorithm>

std::sort(cone, cone + 10,
          [](ClassOne const & a, ClassOne const & b) -> bool
          { return a.value < b.value; } );

If you're willing to define a comparison operator globally, you don't even need the lambda:

bool operator<(ClassOne const & a, ClassOne const & b)
{
    return a.value < b.value;
}

std::sort(cone, cone + 10);

Or you could make the comparator a member function. Or you could give the comparator function a custom name and pass that as the third argument of sort. This might be a good idea in the case where the comparison is specific to your situation and not "natural":

bool ValueCmp(ClassOne const & a, ClassOne const & b)
{
    return a.value < b.value;
}

std::sort(cone, cone + 10, ValueCmp);

The last version is useful if you don't have C++11 support (for lambdas, as in the first case), or if you want to reuse the comparator in multiple different situations.

like image 62
Kerrek SB Avatar answered Oct 14 '22 22:10

Kerrek SB