2017-01-30 33 views
1

我有三個隨機訪問迭代器parentchild1child2,它們指向置換數組中的某些值。 (上下文:我正在實現heapsort;那些迭代器包含一個二進制子樹)。在迭代器上檢索最大值

我需要確定迭代器,它具有最大的參考值(以保持堆的最大堆屬性)。所以,如果*parent是最大的,返回parent,如果*child1是最大的,返回child1

僞代碼:

#include <algorithm> 

auto iterator = std::max({ parent, child1, child2 }); 

iterator現在是其潛在價值是最大的迭代器。

問題是,使用這個文字僞代碼,std::max會在這裏比較迭代器本身,而不是它們的引用值。我可以做std::max({ *parent, *child1, *child2 }),但它返回decltype(*parent),那麼我怎樣才能從那裏獲取迭代器?

我知道使用if s很簡單,但是沒有更優雅的方法嗎?標準庫在那裏有東西嗎?我嘗試了幾件事,但它們看起來都很龐大而且不方便。

回答

3

如果不考慮std::max與自定義比較笨重的,那就是:

auto iterator = std::max({ parent, child1, child2 }, 
         [](auto it_a, auto it_b) { return *it_a < *it_b; }); 
2

std::max接受一個比較函數對象:

auto iterator = std::max({ parent, child1, child2 }, 
         [](const auto& a, const auto& b){ 
    return *a < *b; 
}); 

雖然,你可能更喜歡重構成一些可重複使用的功能部件:

template<class Fun> 
auto indirect_args(Fun&& fun = {}) { 
    return [fun = std::forward<Fun>(fun)](auto&&... args) { 
     std::forward<decltype(fun)>(fun)(
      *std::forward<decltype(args)>(args)...); 
    }; 
} 

auto iterator = std::max({ parent, child1, child2 }, 
         indirect_args<std::less<decltype(parent)>>(); 
}); 
2

因爲std::max有一個自定義的比較器的過載,你可以這樣做:

auto cmp = [](auto lhs, auto rhs){ return *lhs < *rhs; }; 
auto iterator = std::max({ parent, child1, child2 }, cmp);