samedi 22 août 2020

using the sort function on vectors on different variables

I've data that has been given in coordinates. I made their classes and the classes are made of this:

Point2D (int x, int y)

Point3D (int z) //#include Point2D.h

Line2D (Point2D pt1, Point2D pt2)

Line3D (Point3D pt1, Point3D pt2)

Now, I'm supposed to be able to sort the data according to any filtering criteria (each class is a filtering criteria), any sorting criteria (x, y, z, or their product) and sorting order (either ascending or descending) The filtering criteria specifies which set of records to be displayed.

I've created a generic sort algorithm, but I'm supposed to be using the sort function from STL algorithm. I'm pasting my algo below, but can someone simplify it using the sort function.

void sort(vector<Point2D *> &point2DList, vector<Point3D *> &point3DList, vector<Line2D *> &line2DList, vector<Line3D *> &line3DList, string filterCriteria, string sortingCriteria, string sortingOrder)
{
    if (filterCriteria == "Point2D")
    {
        for (int i = 0; i < (int)point2DList.size() - 1; i++)
        {
            int index = i;
            for (int j = i + 1; j < point2DList.size(); j++)
            {
                if (sortingOrder == "ASC")
                {
                    if ((sortingCriteria == "x-ordinate" && point2DList[index]->getX() > point2DList[j]->getX()) || (sortingCriteria == "y-ordinate" && point2DList[index]->getY() > point2DList[j]->getY()))
                        index = j;
                }
                else if (sortingOrder == "DSC")
                {
                    if ((sortingCriteria == "x-ordinate" && point2DList[index]->getX() < point2DList[j]->getX()) || (sortingCriteria == "y-ordinate" && point2DList[index]->getY() < point2DList[j]->getY()))
                        index = j;
                }
            }
            Point2D *ptr = point2DList[i];
            point2DList[i] = point2DList[index];
            point2DList[index] = ptr;
        }
    }

I've only pasted the first part of the algo that involves the Point2D objects, same flow I've applied for the other 3 classes as well. Please help

Aucun commentaire:

Enregistrer un commentaire