'How to sort diferent type of lists with template in C++
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.
}
};
Solution 1:[1]
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;});
Solution 2:[2]
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).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
