0

I have a program that creates an array of pointers to an object. The class the pointers are pointing to stores the net price of an item and has a function for calculating the gross price of the object.

Product *p[10];

Book *b;
Software *s;

double price;

cout << "Enter the price of the book: " << endl;
cin >> price;

b = new Book(price);

cout << "Enter the price of the software: " << endl;
cin >> price;

s = new Software(price);

cout << "Gross price of book: " << b->getGrossPrice() << endl;
cout << "Gross price of software: " << s->getGrossPrice() << endl;

p[0] = b;
p[1] = s;

Is there a way of sorting the array in ascending order of the gross price?

I know there is a sort algorithm in the STL but I don't think it will work for me or at least I'm not sure how to make it work.

There are solutions to similar problems on the site that use sort however none that I can find show it's used in this context.

2
  • is getGrossPrice() virtual? then you can just call sort with a custom functor that calls that Commented Jan 25, 2017 at 19:24
  • 1
    Possible duplicate of <algorithm> vector sort with objects? Commented Jan 25, 2017 at 19:26

2 Answers 2

4
std::sort(p, p+n,
          [](Product* p1, Product* p2)
          {
              return p1->getGrossPrice() < p2->getGrossPrise();
          }); 

This is a call to the standard sorting function std::sort. We pass the begin and end iterators(pointers, in this case) to the range we with to sort, and a third argument which is a function object that returns true its first argument is strictly less (in terms of the strict weak ordering we want to sort according to) than the second argument and false otherwise. The part that starts with [] is called a lambda-expression: in other languages similar objects can be known as anonymous functions. It was introduced in C++11.

Sign up to request clarification or add additional context in comments.

5 Comments

Amen, Please don't just post code. This is not helpful for the asker to understand the answer. If you can, edit the answer and add a brief explanation.
Might want to add C++11 > and maybe add a solution for pre.
Have a little patience, guys.
@ArmenTsirunyan Regarding your plea for patience : it's reasonable to assume that once someone posts an answer, it's the complete answer they intended to post. People are right to critic an answer immediately.
@FrançoisAndrieux On the other hand the SO system encourages First to post, so Armens procedure is a common one. It is also encouraged by Jon Skeet.
0

With range-v3, you can simply do (with projection):

ranges::sort(prods, std::less<>{}, &Product::getGrossPrice);

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.