I got a parent class call
Shape
Shape got 2 child call
Square and Rectangle
Shape class got a variable call area, which is of int type
So i created some object of Square, Rectangle like this
int main()
{
Shape *shaped[100];
//then i did some adding of object..
int areaValue;
areaValue=1;
shaped[0] = new Rectangle();
shaped[0]->setArea(areaValue);
areaValue=7;
shaped[1] = new Square();
shaped[1]->setArea(areaValue);
areaValue=5;
shaped[2] = new Square();
shaped[2]->setArea(areaValue);
shapeCounter = 3;
sort(shaped[0],shaped[2]);
for (int i=0;i<shapeCounter;i++)
{
cout << shaped[i].getArea() << endl;
}
}
I try to sort by ascending area but it doesnt work. no position change, the area still in the same sequence.
Thanks for all help!
Update:
I did the following changes at Shape.cpp
bool Shape::orderByArea(const Shape* lhs, const shape* rhs)
{
return lhs->area() < rhs->area();
}
Then at main.cpp I did this
std::sort(shaped, shaped + 3, orderByArea);
however i get an error, orderByArea was not declared in this scope.
Another thing i tried was:
To sort using vector
At Shape.h
public:
bool operator<const Shape& x) const
{
return area < x.area;
}
At main.cpp
vector<ShapeTwoD*> sortVector;
sortVector.clear();
sortVector.assign(shaped,shaped + shapeCounter);
sort(sortVector.begin(),sortVector.end());
for(int i=0;i<shapeCounter;i++)
{
cout << sortVector[i].toDisplay() << endl;
}
But nothing seems sorted. I try do a printout its position is same.
Updates: Its fixed now. sort is working . Thanks to the experts !
I got another question is
Shape *shaped[100];
How do i copy the value of
Shape *shaped[100];
into
vector<Shape> myVector;
instead of
vector<Shape*> myVector;
so i can use the normal object sort.
In your code how did you expect the compiler to know that you wanted to sort by area, magic? I would recommend reading a book on the standard C++ library (aka the STL), it will explain how to do custom sorting. In your code you have an array of pointers, so you should write a functor that can order your pointers. Also your parameters to std::sort are wrong. Your array starts at
shaped, and ends atshaped + 3(since you have three elements in your array).Untested code, apologies for any mistakes.
Or you can use a function pointer as juanchopanza says.