简体   繁体   English

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

[英]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*> ?是否可以编写一个可以对vector<MyType>vector<MyType*>进行排序的 function ?

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> .当我有std::vector<MyType>时效果很好。 But now I want to sort a std::vector<MyType*> and I want to use the exact same logic.但是现在我想对std::vector<MyType*>进行排序,并且我想使用完全相同的逻辑。 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.如果您抽象出“获取价值”部分,您可以重复使用大部分 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);
    });
}

Where在哪里

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