Jack in the Box
Jack in the Box

Reputation: 137

Sorting an input array of objects in C++

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

Upvotes: 0

Views: 196

Answers (2)

juanchopanza
juanchopanza

Reputation: 227390

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);

Upvotes: 3

MadScientist
MadScientist

Reputation: 3460

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();
});

Upvotes: 1

Related Questions