std::ranges::min
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
呼叫簽名 (Call signature) |
||
template< class T, class Proj = std::identity, std::indirect_strict_weak_order< |
(1) | (C++20 起) |
template< std::copyable T, class Proj = std::identity, std::indirect_strict_weak_order< |
(2) | (C++20 起) |
template< ranges::input_range R, class Proj = std::identity, std::indirect_strict_weak_order< |
(3) | (C++20 起) |
返回給定投影元素中較小的一個。
1) 返回 a 和 b 中較小的一個。
2) 返回初始化列表 r 中的第一個最小元素。
3) 返回範圍 r 中的第一個最小元素。
本頁描述的類函式實體是 演算法函式物件(非正式地稱為 niebloids),即
目錄 |
[編輯] 引數
a, b | - | 要比較的值 |
r | - | 要比較的值的範圍 |
comp | - | 應用於投影元素的比較 |
proj | - | 應用於元素的投影 |
[編輯] 返回值
1) 根據投影,a 和 b 中較小的一個。如果它們等價,返回 a。
[編輯] 複雜度
1) 恰好進行一次比較。
2,3) 恰好進行 ranges::distance(r) - 1 次比較。
[編輯] 可能的實現
struct min_fn { template<class T, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<const T*, Proj>> Comp = ranges::less> constexpr const T& operator()(const T& a, const T& b, Comp comp = {}, Proj proj = {}) const { return std::invoke(comp, std::invoke(proj, b), std::invoke(proj, a)) ? b : a; } template<std::copyable T, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<const T*, Proj>> Comp = ranges::less> constexpr T operator()(std::initializer_list<T> r, Comp comp = {}, Proj proj = {}) const { return *ranges::min_element(r, std::ref(comp), std::ref(proj)); } template<ranges::input_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less> requires std::indirectly_copyable_storable<ranges::iterator_t<R>, ranges::range_value_t<R>*> constexpr ranges::range_value_t<R> operator()(R&& r, Comp comp = {}, Proj proj = {}) const { using V = ranges::range_value_t<R>; if constexpr (ranges::forward_range<R>) return static_cast<V>(*ranges::min_element(r, std::ref(comp), std::ref(proj))); else { auto i = ranges::begin(r); auto s = ranges::end(r); V m(*i); while (++i != s) if (std::invoke(comp, std::invoke(proj, *i), std::invoke(proj, m))) m = *i; return m; } } }; inline constexpr min_fn min; |
[編輯] 注意
如果其中一個引數是臨時物件並且該引數被返回,則透過引用捕獲 `std::ranges::min` 的結果會產生懸空引用。
int n = -1; const int& r = std::ranges::min(n + 2, n * 2); // r is dangling
[編輯] 示例
執行此程式碼
#include <algorithm> #include <iostream> #include <string> int main() { namespace ranges = std::ranges; using namespace std::string_view_literals; std::cout << "smaller of 1 and 9999: " << ranges::min(1, 9999) << '\n' << "smaller of 'a', and 'b': '" << ranges::min('a', 'b') << "'\n" << "shortest of \"foo\", \"bar\", and \"hello\": \"" << ranges::min({"foo"sv, "bar"sv, "hello"sv}, {}, &std::string_view::size) << "\"\n"; }
輸出
smaller of 1 and 9999: 1 smaller of 'a', and 'b': 'a' shortest of "foo", "bar", and "hello": "foo"
[編輯] 另請參閱
(C++20) |
返回給定值中較大的那個 (演算法函式物件) |
(C++20) |
返回兩個元素中較小和較大的一個 (演算法函式物件) |
(C++20) |
返回一個範圍中最小的元素 (演算法函式物件) |
(C++20) |
將值限制在邊界值對之間 (演算法函式物件) |
返回給定值中較小的那個 (函式模板) |