Is it possible to write a single function that can sort a vector<MyType> or a vector<MyType*>?
I have the existing bit of code
template <class Iterator>
void SortMyType(Iterator first, Iterator last) {
std::sort(first, last, [](const MyType& a, const MyType& b) {
return a.some_value() < b.some_value();
});
}
which works great when I have std::vector<MyType>. But now I want to sort a std::vector<MyType*> and I want to use the exact same logic. Is it possible to do such a thing?
You can re-use most of that function if you abstract away the "get the value" part.
template <class Iterator>
void SortMyType(Iterator first, Iterator last) {
using ObjeceType = decltype(*first);
std::sort(first, last, [](const ObjectType& a, const ObjectType& b) {
return getValue(a) < getValue(b);
});
}
Where
ReturnType getValue(MyType const& o)
{
return o.some_value;
}
ReturnType getValue(MyType const* p)
{
return getValue(*p);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With