繁体   English   中英

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

[英]Sort vector of elements or pointers to elements

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

我有现有的代码

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*>进行排序,并且我想使用完全相同的逻辑。 有可能做这样的事情吗?

如果您抽象出“获取价值”部分,您可以重复使用大部分 function。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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