So I've created a vector which contains product objects. The product has a int ID, string manufacturer and string productname. Lets say I've stored a few products by doing this
vector<product*>productlist;
Product*p = new Product(123, "Sony", "C vaio laptop")
Product*p1 = new Product(1234, "LG", "D 54 inch TV")
Product*p2 = new Product(1235, "Lays", "A potato chips")
productlist.push_back(p);
productlist.push_back(p1);
productlist.push_back(p2);
I have a method called getproductname(){return productname;} which can be used to get the productname, and I can sort the productnames, but after that I have no idea how to continue as I don't know how to print the whole object by alphabetically of their productname.
Now I want to sort/print the 3 products by alphabetical order of their productname. How can I do that(the sorting part)? Sample output:
Products sorted alphabetically
Product ID1: 1235
Product manufacturer: Lays
Product name:A potato chips //name starts with A so it's the first output
Product ID2: 123
Product manufacturer: Sony
Product name: C vaio laptop
Product ID3: 1234
Product manufacturer: LG
Product name: D 54 inch TV //name starts with D so it's the last
I've tried inserting sort(productlist.begin(), productlist.end()); but it only works on vectors with string and not objects.
question asked was too vague/simple at first. Edited!
The easiest way is to use
std::sort()
function from the standard library. You can try something like this:I would recommend you look into the documentation for more details on
std::sort
The way to make sorting happen using
STL
containers is to define a comparator function that tells thestd::sort
algorithm how to compare the elements to place them in order. So we need to define a less than relationship which we can do by creating a less than operator for ourProduct
class like this:Now if we send a container full of
Product
objects tostd::sort
they will be sorted according to name.However, we need to sort
Product
objects through their pointers so we need another less than operator to hand to thestd::sort
function that dereferences the pointers before making the comparison using our comparator function.Now we have those two we can call our
std::sort
algorithm: