对元素的向量或指向元素的指针进行排序

Sort vector of elements or pointers to elements

本文关键字:元素 排序 指针 向量      更新时间:2023-10-16

是否可以编写一个可以对vector<MyType>vector<MyType*>进行排序的函数?

我有现有的代码

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

当我有std::vector<MyType>时效果很好.但是现在我想对std::vector<MyType*>进行排序,我想使用完全相同的逻辑。有可能做这样的事情吗?

如果你抽象出"获取值"部分,你可以重用该函数的大部分。

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

哪里

ReturnType getValue(MyType const& o)
{
   return o.some_value;
}
ReturnType getValue(MyType const* p)
{
    return getValue(*p);
}
相关文章: