名稱空間
變體
操作

std::ranges::get(std::ranges::subrange)

來自 cppreference.com
< cpp‎ | ranges‎ | subrange
 
 
範圍庫 (Ranges library)
範圍介面卡 (Range adaptors)
 
 
定義於標頭檔案 <ranges>
template< std::size_t N, class I, class S, ranges::subrange_kind K >

    requires ((N == 0 && std::copyable<I>) || N == 1)

constexpr auto get( const ranges::subrange<I, S, K>& r );
(1) (C++20 起)
template< std::size_t N, class I, class S, ranges::subrange_kind K >

    requires (N < 2)

constexpr auto get( ranges::subrange<I, S, K>&& r );
(2) (C++20 起)
namespace std { using ranges::get; }
(3) (C++20 起)

提供結構化繫結支援。

1)N == 0N == 1 時,分別從 subrange 左值(或 const 右值)獲取迭代器或哨兵。
2)(1) 相同,但它接受非 const 的 subrange 右值。
3) 過載 (1,2) 被匯入到名稱空間 std 中,這簡化了它們的使用,並使每個帶有可複製迭代器的 subrange 成為類對(pair-like)型別。

目錄

[編輯] 引數

r - 一個 subrange

[編輯] 返回值

1,2) 如果 N0,返回 r.begin()。否則(N1),返回 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)N0 時複製 begin_,但 I 可能不支援 copyable 已新增約束

[編輯] 另請參閱

結構化繫結 (C++17) 將指定的名稱繫結到初始化器的子物件或元組元素[編輯]
tuple 訪問指定的元素
(函式模板) [編輯]
訪問 pair 的元素
(函式模板) [編輯]
訪問 array 的一個元素
(函式模板) [編輯]
根據索引或型別(如果型別唯一)讀取變體的值,出錯時丟擲異常
(函式模板) [編輯]
std::complex 獲取實部或虛部的引用
(函式模板) [編輯]