std::ranges::max_element
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
呼叫簽名 (Call signature) |
||
template< std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<I, Proj>> Comp = ranges::less > |
(1) | (C++20 起) |
template< ranges::forward_range R, class Proj = std::identity, std::indirect_strict_weak_order< |
(2) | (C++20 起) |
1) 在範圍
[
first,
last)
中查詢最大元素。本頁描述的類函式實體是 演算法函式物件(非正式地稱為 niebloids),即
目錄 |
[編輯] 引數
first, last | - | 定義要檢查的元素 範圍 的迭代器-哨兵對 |
r | - | 要檢查的 range |
comp | - | 應用於投影元素的比較 |
proj | - | 應用於元素的投影 |
[編輯] 返回值
指向範圍 [
first,
last)
中最大元素的迭代器。若範圍中有數個元素等價於最大元素,則返回指向第一個此類元素的迭代器。若範圍為空(即 first == last),則返回 last。
[編輯] 複雜度
恰好 max(N - 1, 0) 次比較,其中 N = ranges::distance(first, last)。
[編輯] 可能的實現
struct max_element_fn { template<std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<I, Proj>> Comp = ranges::less> constexpr I operator()(I first, S last, Comp comp = {}, Proj proj = {}) const { if (first == last) return last; auto largest = first; while (++first != last) if (std::invoke(comp, std::invoke(proj, *largest), std::invoke(proj, *first))) largest = first; return largest; } template<ranges::forward_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less> constexpr ranges::borrowed_iterator_t<R> operator()(R&& r, Comp comp = {}, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), std::ref(comp), std::ref(proj)); } }; inline constexpr max_element_fn max_element; |
[編輯] 示例
執行此程式碼
#include <algorithm> #include <cmath> #include <iostream> int main() { namespace ranges = std::ranges; const auto v = {3, 1, -14, 1, 5, 9, -14, 9}; auto result = ranges::max_element(v.begin(), v.end()); std::cout << "Max element at pos " << ranges::distance(v.begin(), result) << '\n'; auto abs_compare = [](int a, int b) { return std::abs(a) < std::abs(b); }; result = ranges::max_element(v, abs_compare); std::cout << "Absolute max element at pos " << ranges::distance(v.begin(), result) << '\n'; }
輸出
Max element at pos 5 Absolute max element at pos 2
[編輯] 參閱
(C++20) |
返回一個範圍中最小的元素 (演算法函式物件) |
(C++20) |
返回範圍中最小和最大的元素 (演算法函式物件) |
(C++20) |
返回給定值中較大的那個 (演算法函式物件) |
返回一個範圍中最大的元素 (函式模板) |