簡體   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