Good evening experts and gurus !!
I have an array object that record the following..
This is at record.h
Class Record
{
private:
string name;
int data;
float valueData;
public:
bool operator<(const Record&) const;
}
and the constructor are created at record.cpp
record.cpp i added this
bool Record::operator<(const Record& rhs) const
{
return valueData < rhs.valueData;
}
At main.cpp I created record Array of Size 10
#include "record.h"
Record rec[10];
I did
sort(&rec[0], &rec[2]);
but nothing seems changing or sorted.. i got 3 element , rec[0], rec[1], rec[2] and i want sort them ,but they are of another header file record.h & its record.cpp which describe above.
Original Question
Next is i recorded several value to the object
and now rec got 3 index
rec[0]
name = "jack1"
data = 1
valueData = 20
rec[1]
name = "jack2"
data = 2
valueData = 15
rec[2]
name = "jack3"
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
rec[2] then rec[0] then rec[1] ..
but i wanna sort by class array object. and re-arrange the value together , how do i achieve this.
the 3 value is private, so i not sure where do i create the sort function, at main.cpp or at record.cpp , next is how do i sort it so it can output in the way below..
-- Highest to lowest --
1) Name: Jack3, Data = 3, Value =25
2) Name: Jack1 , Data =1 , Value = 20
3) Name: Jack2, Data = 2, Value = 15
Thanks for all help and guide!!
Use
std::sortin conjunction with something that compares twoRecords. There are at least 3 ways to provide this compoarison.1: Implement an
operator<onRecord:…then:
2: Provide a functor:
…then:
3: (If you have a C++11 compiler) Use a lambda:
EDIT:
Here is a complete sample that shows how to use the first method: