std::ranges::min_element
從 cppreference.com
在標頭 <algorithm> 定義
|
||
調用簽名 |
||
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)
中的最小元素。此頁面上描述的函數式實體是算法函數對象(非正式地稱為 niebloid),即:
目錄 |
[編輯] 參數
first, last | - | 要檢驗的元素範圍的迭代器-哨位對 |
r | - | 待檢驗 range
|
comp | - | 應用到投影后元素的比較 |
proj | - | 應用到元素的投影 |
[編輯] 返回值
指向範圍 [
first,
last)
中最小元素的迭代器。若數個元素等價於最小元素,則返回指向首個這種元素的迭代器。若範圍為空(即 first == last)則返回比較等於 last 的迭代器。
[編輯] 複雜度
準確 max(N-1,0) 次比較,其中 N = ranges::distance(first, last)。
[編輯] 可能的實現
struct min_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 smallest = first; while (++first != last) if (std::invoke(comp, std::invoke(proj, *first), std::invoke(proj, *smallest))) smallest = first; return smallest; } 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 min_element_fn min_element; |
[編輯] 示例
運行此代碼
#include <algorithm> #include <array> #include <cmath> #include <iostream> int main() { namespace ranges = std::ranges; std::array v{3, 1, -13, 1, 3, 7, -13}; auto iterator = ranges::min_element(v.begin(), v.end()); auto position = ranges::distance(v.begin(), iterator); std::cout << "最小的元素是 v[" << position << "] == " << *iterator << '\n'; auto abs_compare = [](int a, int b) { return (std::abs(a) < std::abs(b)); }; iterator = ranges::min_element(v, abs_compare); position = ranges::distance(v.begin(), iterator); std::cout << "|min| 元素是 v[" << position << "] == " << *iterator << '\n'; }
輸出:
最小的元素是 v[2] == -13 |min| 元素是 v[1] == 1
[編輯] 參閱
(C++20) |
返回範圍中最大元 (算法函數對象) |
(C++20) |
返回範圍中的最小元和最大元 (算法函數對象) |
(C++20) |
返回給定值中較大者 (算法函數對象) |
返回範圍中最小元 (函數模板) |