std::counted_iterator
來自 cppreference.com
< cpp | 迭代器 (iterator)
定義於標頭檔案 <iterator> |
||
template< std::input_or_output_iterator I > class counted_iterator; |
(C++20 起) | |
std::counted_iterator
是一個迭代器介面卡,其行為與底層迭代器完全相同,不同之處在於它跟蹤到其範圍末尾的距離。當且僅當其計數達到零時,此迭代器等於 std::default_sentinel。
目錄 |
[編輯] 成員型別
成員型別 | 定義 |
iterator_type
|
I
|
value_type (有條件存在) |
std::iter_value_t<I> 如果 I 建模 indirectly_readable ;否則,未定義 |
difference_type
|
std::iter_difference_t<I> |
iterator_concept (有條件存在) |
I::iterator_concept 如果存在;否則,未定義 |
iterator_category (有條件存在) |
I::iterator_category 如果存在;否則,未定義 |
[編輯] 成員物件
成員名稱 (Member name) | 定義 |
current (私有) |
base() 訪問的底層迭代器(僅用於闡釋的成員物件*) |
length (私有) |
底層迭代器與其範圍末尾之間的距離 (僅用於闡釋的成員物件*) |
[編輯] 成員函式
構造新的 counted_iterator (公共成員函式) | |
賦值另一個 counted_iterator (公共成員函式) | |
訪問底層迭代器 (公共成員函式) | |
返回到末尾的距離 (公共成員函式) | |
訪問指向的元素 (公共成員函式) | |
透過索引訪問元素 (公共成員函式) | |
遞增或遞減 counted_iterator (公共成員函式) |
[編輯] 非成員函式
(C++20) |
比較到末尾的距離 (函式模板) |
檢查到末尾的距離是否等於 0 (函式模板) | |
(C++20) |
前進迭代器 (函式模板) |
(C++20) |
計算兩個迭代器介面卡之間的距離 (函式模板) |
計算到末尾的帶符號距離 (函式模板) | |
(C++20) |
將底層迭代器解引用的結果轉換為其關聯的右值引用型別 (函式) |
(C++20) |
交換兩個底層迭代器指向的物件 (函式模板) |
[編輯] 輔助類
為 std::counted_iterator 型別的屬性提供統一介面 (類模板特化) |
[編輯] 示例
執行此程式碼
#include <algorithm> #include <iostream> #include <iterator> #include <string> #include <vector> using std::operator""s; void print(auto const remark, auto const& v) { const auto size = std::ssize(v); std::cout << remark << '[' << size << "] { "; for (auto it = std::counted_iterator{std::cbegin(v), size}; it != std::default_sentinel; ++it) std::cout << *it << (it.count() > 1 ? ", " : " "); std::cout << "}\n"; } int main() { const auto src = {"Arcturus"s, "Betelgeuse"s, "Canopus"s, "Deneb"s, "Elnath"s}; print("src", src); std::vector<decltype(src)::value_type> dst; std::ranges::copy(std::counted_iterator{src.begin(), 3}, std::default_sentinel, std::back_inserter(dst)); print("dst", dst); }
輸出
src[5] { Arcturus, Betelgeuse, Canopus, Deneb, Elnath } dst[3] { Arcturus, Betelgeuse, Canopus }
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
P2259R1 | C++20 | 未提供成員 typedef std::incrementable_traits 專門用於 counted_iterator |
新增成員 typedef 以解決 iterator_traits 修復 刪除冗餘的 std::incrementable_traits 特化 |
[編輯] 另請參閱
(C++20) |
用於知道其範圍邊界的迭代器的預設哨兵 (類) |
(C++20) |
從迭代器和計數建立子範圍 (定製點物件) |
(C++20) |
由另一個view 的前N個元素組成的view (類模板) (範圍介面卡物件) |