Reputation: 119
If there is a struct:
#include <algorithm>
#include <vector>
#include <iomanip>
#include <string>
using namespace std;
bool pred(string *a, string *b){
return *a < *b;
}
struct Student {
int ID;
int age;
double gpa;
string firstname;
string lastname;
};
int main () {
vector<Student*>v;
vector<Student*>v_sortedFirstName;
//both filled with same information
// sort v_sortedFirstName by first name
sort(v_sortedFirstName.begin(), v_sortedFirstName.end(), pred);
}
Now lets say the vector v
is filled with information, and v_sortedFirstName
is filled with the same information (points to the same spots as v
). How would I (using the STL sort function, sort v_sortedFirstName
by firstname?
I was thinking this line: sort(v_sortedFirstName.begin(), v_sortedFirstName.end(), pred);
should be something along the lines of sort(v_sortedFirstName->firstname.begin(), v_sortedFirstName->firstname.end(), pred);
but that doesn't work.
Also, if you guys do not mind, I would like to stick with my predicate function above and not use Lambda as I have not learned that yet.
Upvotes: 0
Views: 652
Reputation: 44258
Your predicate has to accept Student *
instead of string *
:
bool pred(Student *a, Student *b){
return a->firtname < b->firtsname;
}
note if you do not intend to modify data change parameters type to const Student *
and that would make your code cleaner and safer (if you put code in pred
, that by mistake tries to modify that structure then compiler will reject to compile and it would be easy to detect and fix that mistake):
bool pred(const Student *a, const Student *b){
return a->firtname < b->firtsname;
}
Upvotes: 3