std::ranges::get(std::ranges::subrange)
來自 cppreference.com
定義於標頭檔案 <ranges> |
||
template< std::size_t N, class I, class S, ranges::subrange_kind K > requires ((N == 0 && std::copyable<I>) || N == 1) |
(1) | (C++20 起) |
template< std::size_t N, class I, class S, ranges::subrange_kind K > requires (N < 2) |
(2) | (C++20 起) |
namespace std { using ranges::get; } |
(3) | (C++20 起) |
提供結構化繫結支援。
1) 當 N == 0 或 N == 1 時,分別從
subrange
左值(或 const 右值)獲取迭代器或哨兵。2) 與 (1) 相同,但它接受非 const 的
subrange
右值。目錄 |
[編輯] 引數
r | - | 一個 subrange |
[編輯] 返回值
1,2) 如果 N 是 0,返回 r.begin()。否則(N 是 1),返回 r.end()。
[編輯] 示例
執行此程式碼
#include <array> #include <iostream> #include <iterator> #include <ranges> int main() { std::array a{1, -2, 3, -4}; std::ranges::subrange sub_a{std::next(a.begin()), std::prev(a.end())}; std::cout << *std::ranges::get<0>(sub_a) << ' ' // == *(begin(a) + 1) << *std::ranges::get<1>(sub_a) << '\n'; // == *(end(a) - 1) *std::get<0>(sub_a) = 42; // OK // *std::get<2>(sub_a) = 13; // Error: index can only be 0 or 1 }
輸出
-2 -4
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 3589 | C++20 | 過載 (1) 在 N 是 0 時複製 begin_ ,但 I 可能不支援 copyable |
已新增約束 |
[編輯] 另請參閱
結構化繫結 (C++17) | 將指定的名稱繫結到初始化器的子物件或元組元素 |
(C++11) |
tuple 訪問指定的元素 (函式模板) |
(C++11) |
訪問 pair 的元素(函式模板) |
(C++11) |
訪問 array 的一個元素(函式模板) |
(C++17) |
根據索引或型別(如果型別唯一)讀取變體的值,出錯時丟擲異常 (函式模板) |
(C++26) |
從 std::complex 獲取實部或虛部的引用 (函式模板) |