Home > Software design >  How to sort diferent type of lists with template in C
How to sort diferent type of lists with template in C

Time:05-19

In my homework my task is to create the FooCl class for these:

    double d[] = {1.3, 0.7, 2.4, 1.5, 6.2, 5.7, 8.6, 9.1};
    FooCl<double> itemsD(d, sizeof(d) / sizeof(d[0]));

    std::string s[] = {"C  ", "Haskell", "Python", "Java"};
    FooCl<std::string> itemsS(s, sizeof(s) / sizeof(s[0]));

    itemsD.mySort();
    itemsS.mySort();

I made a constructor/destructor for it, but I don't know how to create two different functions with templates for the two different types of lists. I think I would need to use some kind of overloading but don't know how.

template <typename T>
class FooCl
{
private:
    T *mItems;
    int mItemsSize;

public:
    FooCl(T items[], int itemsSize)
    {
        mItems = new T[itemsSize];
        for (int i=0; i<itemsSize;   i)
        {
            this->mItems[i] = items[i];
        }
        this->mItemsSize = itemsSize;
    };

    ~FooCl()
    {
        delete[] mItems;
    }

    void mySort()
    {
        //I have no idea how to write this function, so it can sort two different types of lists.
    }
};

CodePudding user response:

The two operations important for sorting is comparison and swapping.

Both double and std::string already have definitions for <, which is the idiomatic comparison operator.

There is already a template std::swap, which is the idiomatic swap function.

You need to write a sort that uses mItems and mItemsSize, comparing items (with <) and swapping those that are in the wrong position (with std::swap).

CodePudding user response:

One way is to use std::sort as shown below:

void mySort()
{
//--vvvvvvvvv------------------------------------>use std::sort
    std::sort(mItems, mItems   mItemsSize);
}

You can even write your sort functionality/implementation which will include the use of mItems and mItemsSize.

CodePudding user response:

If you want to sort any container like std::array or std::vector

template <typename Container, typename Func>
void sort(Container& c, Func functor)
{
    std::sort(std::begin(c), std::end(c), functor);
}

usage

std::vector<int> vct {1,2,3,1,2};
sort(vct, [](const int lhs, const int rhs) {return lhs > rhs;});
  • Related