简体   繁体   中英

Sort vector of elements or pointers to elements

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM