Hey guys! I was wondering if anybody could help me out with my C++ programming.
I'm currently trying to sort out a vector of class objects by their member variable but i dont know what i'm doing wrong or missing.
I googled alot of things and read through alot of examples on many websites but i always have some kind of problem applying them to my own code.
So here is my code:
class tropicalfruit //Class tropicalfruit
{
public:
string name;
double price;
};
bool sortByName(tropicalfruit &A, tropicalfruit &B) //function to sort fruits by names
{
return (A.name < B.name);
}
bool sortByPrice(tropicalfruit &A, tropicalfruit &B) //function to sort fruits by price
{
return (A.price < B.price);
}
int main()
{
int sortchoice;
/*sample fruit names and prices*/
string fruitname[] = {"avocado", "Watermelon", "Mango", "Pineapple", "Apple", "Orange", "Honeydew", "Pear", "Banana", "Durian"};
double fruitprice[] = {0.8, 4.8, 0.6, 2.4, 0.4, 0.3, 3.1, 0.7, 3.5, 3.8};
vector<tropicalfruit> fruitlist; //vector used to store tropicalfruit class objects
tropicalfruit fruit; //tropicalfruit class object
for(int i=0; i<10; i++) /*puts 10 objects with name and price into vector*/
{
fruit.name = fruitname[i];
fruit.price = fruitprice[i];
fruitlist.push_back(fruit);
}
for(int i=0; i<10; i++) /*displays all fruits' names and prices*/
{
cout << fruitlist[i].name << " " << fruitlist[i].price << endl;
}
cout << endl;
cout<<"Arrange fruits by 1)Name or 2)Price : "; //asks user whether to sort by name or price
cin>>sortchoice;
if(sortchoice == 1)
{
fruitlist.sort(sortByName); //sort fruits by name
}
else if(sortchoice == 2)
{
fruitlist.sort(sortByPrice); //sort fruits by price
}
for(int i=0; i<10; i++) /*displays sorted fruits*/
{
cout << fruitlist[i].name << " " << fruitlist[i].price << endl;
}
cout << endl;
}
I know it looks abit different from any example but i thought that working on my original code was better than working on a code that has bits and pieces of whatever i found on the web :)
the 2 "bool ...." functions were what i saw from my friend's code.
he was able to sort the fruits out but he used a list of objects not a vector of objects. So i actually wanna know how i can sort a vector of objects (as simple as possible).