Virutal base pointer sort question
Jul 16, 2011 at 12:08am UTC
I am trying to sort using base pointers to an array of derived objects. My issue is the sort needs to access a function for each derived class that calculates area of which ever derived object it is sorting through. How can I swap a value that is part of a function and not a member variable of the derived class? I created a setArea function but, the compiler doesn't like it,nor do I think it would work. Here is was I have so far, any help would be greatly appreciated.
Thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
void Shape::sortShape (Shape* array, int numShapes)
{
for (int i = numShapes; i >= 1; i--)
{
for (int itr = 0; itr != itr + i; ++itr)
{
if (itr > itr + 1)
{
double temp;
temp = array[itr].getArea();
array[itr].setArea(array[itr+1].getArea());
array[itr+1].setArea(temp);
}
}
}
}
set Function
1 2 3 4 5 6 7
float Rectangle::setArea(float area)
{
float a = getArea();
return a;
}
Jul 16, 2011 at 12:48am UTC
Jul 16, 2011 at 1:24am UTC
Your set Function does not set anything.
I am trying to sort using base pointers to an array of derived objects.
In that case you need to provide a comparator function
1 2 3
bool cmp( const base *A, const base *B){
return A->area() < B->area(); //using polymorphism
}
How can I swap a value that is part of a function and not a member variable of the derived class?
¿eh? you will be swapping the
pointers
Jul 16, 2011 at 1:47am UTC
Update... just realized that I should be swapping the objects/pointers not the area. This avoids the use of a set function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
void Shape::sortShape (Shape* array[], int numShapes)
{
for (int i = numShapes; i >= 1; i--)
{
for (int itr = 0; itr != itr + i; ++itr)
{
if (array[itr]->getArea() < array[itr + i]->getArea())
{
Shape* temp;
temp = array[itr];
array[itr] = array[itr+1];
array[itr+1] = temp;
}
}
}
Last edited on Jul 16, 2011 at 1:47am UTC
Topic archived. No new replies allowed.