0

I have a base class Shape, and other derived classes Circle, Square and Triangle. I created vector of three base-class pointers.

vector < Shape * > shapes( 3 );
shapes[ 0 ] = &C1; //Circle C1;
shapes[ 1 ] = &S1; //Square S1;
shapes[ 2 ] = &T1; //Triangle T1;

After that, I used a loop to call virtualViaPointer() that would call the virtual function draw()

for (size_t i = 0; i < shapes.size(); ++i) {
    cout << endl;
    virtualViaPointer( shapes[ i ] );
}

void virtualViaPointer(const Shape * const baseClassPtr)
{
baseClassPtr->draw();
}

Each derived class has a function getArea() that calculates the area of each shape and returns the result.

Now, I want to sort the areas by using the vector above, and calling getArea() functions. How can I do that? For example, my sort function should be like this sortShape(Array, numShape), where Array is an array of Shape pointers pointing to the created shapes.

Any help is appreciated

2 Answers 2

3

You can use std::sort with a suitable comparison function:

bool compareArea(const Shape* lhs, const Shape* rhs){
  return lhs->getArea() < rhs->getArea();
}

...

std::sort(shapes.begin(), shapes.end(), compareArea);
Sign up to request clarification or add additional context in comments.

Comments

1

Use the sort algorithms with a user-defined sorting criterion, e.g.

std::sort(shapes.begin(), shapes.end(), [](Shape * lhs, Shape * rhs)
{
  return lhs->getArea() < rhs->getArea();
});

2 Comments

This is cool but please also note that it requires a modern compiler.
It would be good to state that using a lambda function is only supported C++11.

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.