Reputation: 31
I just wrote a program where program sorts people by time(minutes).But what and where should I add a code, if minutes are the same and I need to sort seconds as well
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
struct people{
string name;
int min;
int sec;
};
bool comp(const people &p1, const people &p2) {return (p1.min < p2.min); }
int main() {
int temp;
people z[6];
for (int i = 0; i < 6; i++) {
cin >> z[i].name;
cin >> z[i].min;
cin >> z[i].sec;
}
sort(z, z + 6, comp);
cout << endl;
for (int i = 0; i < 6; i++) {
cout << z[i].name << " " << z[i].min << " " << z[i].sec << endl;
}
return 0;
}
/*
input for example:
John 19 15
Liza 9 59
Michael 19 45
Kira 2 37
Thomas 5 41
Justas 19 24
*/
Upvotes: 1
Views: 58
Reputation: 5714
The answers of @Jarod42 and @doug will work for sure, but I think this solution is more readable.
int getSeconds(const people &p){
const min2sec = 60.0;
return p.min * min2sec + p.sec;
}
bool comp(const people &p1, const people &p2) {
return (getSeconds(p1) < getSeconds(p2));
}
The solution of @doug might yield a performance advantage, since you compare the minutes first and only if they are not equal you look at the seconds.
If performance turns out to be an issue (and measurements proof that this is your hotspot), you can optimise this. Keep in mind that the data structure contains superfluous data (string name;
) for this operation, which might spoil your performance due to cache line jams.
Upvotes: 0
Reputation: 218268
A easy way to have a correct comparison function is to use operator <
of std::tuple
:
bool comp(const people &lhs, const people &rhs)
{
return std::tie(lhs.min, lhs.sec) < std::tie(rhs.min, rhs.sec);
}
Upvotes: 2
Reputation: 4299
Just add a conditional for .sec when p1.min==p2.min
bool comp(const people &p1, const people &p2) {
return (p1.min < p2.min || p1.min == p2.min && p1.sec < p2.sec); }
Upvotes: 1