std::move_iterator
來自 cppreference.com
< cpp | 迭代器 (iterator)
定義於標頭檔案 <iterator> |
||
template< class Iter > class move_iterator; |
(C++11 起) | |
std::move_iterator
是一個迭代器介面卡,其行為與底層迭代器(必須至少是 LegacyInputIterator 或模型 input_iterator
(C++20 起),或更強的迭代器概念(C++23 起))完全一致,只是解引用時會將底層迭代器返回的值轉換為右值。如果此迭代器用作輸入迭代器,則效果是從中移動值,而不是從中複製值。
目錄 |
[編輯] 巢狀型別
|
(C++20 前) | ||||||||||||||||||||
|
(C++20 起) |
[編輯] 資料成員
成員 | 描述 |
Iter current |
底層迭代器 (僅用於闡釋的成員物件*) |
[編輯] 成員函式
構造一個新的 move_iterator (公共成員函式) | |
賦值另一個 move_iterator (公共成員函式) | |
訪問底層迭代器 (公共成員函式) | |
訪問指向的元素 (公共成員函式) | |
透過索引訪問元素 (公共成員函式) | |
遞增或遞減 move_iterator (公共成員函式) |
[編輯] 非成員函式
(C++11)(C++11)(在 C++20 中移除)(C++11)(C++11)(C++11)(C++11)(C++20) |
比較底層迭代器 (函式模板) |
比較底層迭代器和底層哨兵 (函式模板) | |
(C++11) |
前進迭代器 (函式模板) |
(C++11) |
計算兩個迭代器介面卡之間的距離 (函式模板) |
計算底層迭代器和底層哨兵之間的距離 (函式模板) | |
(C++20) |
將底層迭代器解引用的結果轉換為其關聯的右值引用型別 (函式) |
(C++20) |
交換兩個底層迭代器指向的物件 (函式模板) |
(C++11) |
建立從引數推導型別的 std::move_iterator (函式模板) |
[編輯] 輔助模板
template< class Iterator1, class Iterator2 > requires (!std::sized_sentinel_for<Iterator1, Iterator2>) |
(C++20 起) | |
此 std::disable_sized_sentinel_for
的偏特化阻止 move_iterator
的特化滿足 sized_sentinel_for
,如果其底層迭代器不滿足該概念。
[編輯] 註解
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_move_iterator_concept |
202207L |
(C++23) | 使 std::move_iterator<T*> 成為隨機訪問迭代器 |
[編輯] 示例
執行此程式碼
#include <algorithm> #include <iomanip> #include <iostream> #include <iterator> #include <ranges> #include <string> #include <string_view> #include <vector> void print(const std::string_view rem, const auto& v) { std::cout << rem; for (const auto& s : v) std::cout << std::quoted(s) << ' '; std::cout << '\n'; }; int main() { std::vector<std::string> v{"this", "_", "is", "_", "an", "_", "example"}; print("Old contents of the vector: ", v); std::string concat; for (auto begin = std::make_move_iterator(v.begin()), end = std::make_move_iterator(v.end()); begin != end; ++begin) { std::string temp{*begin}; // moves the contents of *begin to temp concat += temp; } // Starting from C++17, which introduced class template argument deduction, // the constructor of std::move_iterator can be used directly: // std::string concat = std::accumulate(std::move_iterator(v.begin()), // std::move_iterator(v.end()), // std::string()); print("New contents of the vector: ", v); print("Concatenated as string: ", std::ranges::single_view(concat)); }
可能的輸出
Old contents of the vector: "this" "_" "is" "_" "an" "_" "example" New contents of the vector: "" "" "" "" "" "" "" Concatenated as string: "this_is_an_example"
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 2106 | C++11 | 解引用 move_iterator 可能會返回懸空引用如果解引用底層迭代器返回純右值 |
返回該 物件代替 |
LWG 3736 | C++20 | move_iterator 缺少 disable_sized_sentinel_for 特化 |
已新增 |
P2259R1 | C++20 | 成員 iterator_category 被定義,即使std::iterator_traits<Iter>::iterator_category 未定義 |
iterator_category 在這種情況下未定義 |
[編輯] 另請參閱
(C++11) |
建立從引數推導型別的 std::move_iterator (函式模板) |
(C++20) |
std::move_iterator 的哨兵介面卡 (類模板) |