Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort vector of elements or pointers to elements

Tags:

c++

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?

like image 408
Nick Chapman Avatar asked Aug 15 '26 08:08

Nick Chapman


1 Answers

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);
}
like image 71
R Sahu Avatar answered Aug 17 '26 22:08

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!