i cannot figure out how sort vector of objects 1 of member variables called vin, of data type string
. either perform bubble sort or selection sort. familiar bubble sort, that's direction attempted take. however, aware need compare both of strings either making them uppercase or lower case. keep in mind, strings have number characters in them well.
so question is: 1) how convert string either lowercase or ascii numbers , 2) data type should temp variable (data type of class or other data type).
here (incomplete) code have far:
void sortinventory(vector<vehicle> &carlist) { bool swap; string temp; { swap = false; (int count = 0; count < carlist.size(); count++) { if (carlist[count].getvin() > carlist[count + 1].getvin()) { temp = carlist[count].getvin(); carlist[count].getvin() = carlist[count + 1].getvin(); carlist[count + 1].getvin() = temp; swap = true; } } } while (swap); }
here class declaration:
class vehicle { private: string vin; public: string getvin(); void setvin(string); };
here class implementation:
string vehicle::getvin() { return vin; } void vehicle::setvin(string input) { vin = input; }
thanks!
you can std::sort(carlist.begin(),carlist.end(),vehiclecompare)
vehiclecompare
comparison function define. see sort documentation. then, uppercase can use std::toupper, shown in this guide.
std::string mytoupper(std::string in) { std::transform(in.begin(), in.end(),in.begin(), ::toupper); return in; }
so comparison operator(*) be:
bool vehiclecompare (const vehicle a, const vehicle b) { const std::string a_name = mytoupper(a.getvin()); const std::string b_name = mytoupper(b.getvin()); return (a_name < b_name); }
useful reading string comparison operator.
by way, string getvin()
method should const
, should change declaration string getvin() const
.
if want keep sorting function, point in case you'll have define proper comparison operator, 1 shown here.
to answer second question, temp
auto
in c++11, or std::string
. way trying assign vin
value wrong. given interface have given, should be:
auto temp = carlist[count].getvin(); carlist[count].setvin(carlist[count + 1].getvin() ); carlist[count + 1].setvin(temp);
although still might nasty when start have more 1 member variable copy: should instead build copy constructor , change code to:
auto temp = carlist[count]; //you can use vehicle instead of auto type carlist[count] = carlist[count + 1]; carlist[count + 1] = temp;
the copy constructor be:
vehicle(const vehicle& in) : vin(in.getvin() ) {}
and, @ point, you'll want constructor string, , empty constructor.
vehicle(std::string& invin) : vin(invin) {} vehicle(const vehicle& in) {} //all input members initialized through default constructor.
(*) note comparison method wouldn't efficient, makes uppercase whole string while first few characters sufficient decide order. more efficient way uppercase 1 character @ time , compare before deciding if uppercase character.