c++ - Sort a vector of objects -
i'm working simple c++ program, class: (i'm beginner programmer)
class car{ private: string newbrand; int newmileage; int newyear; double newprice;
(i didn't post public classes)
bool sortbyname(car &carvector) { return carvector.getbrand() < carvector.getbrand(); }
main:
int main(){ vector<car> carvector; readfile(carvector); listcar(carvector); return 0; }
list car functions, when call function "sort", order vector of objects name:
void listcar(vector<car>&carvector){ int i, op; system("cls"); sort(carvector.begin(), carvector.end(), sortbyname); cout << "menu::car list name" << endl; cout << ":brand: \t:mileage: \t:year: \t\t:price:" << endl; for(i=0; i<carvector.size();i++) { cout << carvector[i].getbrand() << " \t\t"; cout << carvector[i].getmileage() << " \t\t"; cout << carvector[i].getyear() << " \t\t"; cout << carvector[i].getprice() << " \t\t"; cout << endl; } { cout << endl << "1.back: "; cin >> op; }while(op!=1); }
i think program supposed work. can me finding error? best regards
in compare function, need use two parameters: should compare these objects each other. also, that's independent of vector (it operates on elements of vector), shouldn't name arguments avoid confusion.
so function this:
bool sortbyname(car &a, car &b) { return a.getbrand() < b.getbrand(); }
additionally, it's choice (but not required) add const
parameteres passed reference in order indicate function body doesn't modify them:
bool sortbyname(const car &a, const car &b) { return a.getbrand() < b.getbrand(); }
but it's necessary put const
@ end of signature of function car::getbrand()
in order indicate that function won't modify object operates on. called const-correctness. mentioned before, process not required (like when using std::sort
) it's style have const-correctness.
or can use lambda if compiler supports (you need enable c++11 support):
std::sort(carvector.begin(), carvector.end(), [](const car &a, const car &b){ return a.getbrand() < b.getbrand(); });
note if you're going compare cars always name, makes sense implement operator<
class. when doing that, don't need specify compare function in call std::sort
, objects compared a < b
instead of yourfunction(a, b)
.
Comments
Post a Comment