std::iota
來自 cppreference.com
定義於標頭檔案 <numeric> |
||
template< class ForwardIt, class T > void iota( ForwardIt first, ForwardIt last, T value ); |
(C++11 起) (C++20 起為 constexpr) |
|
用從 value 開始並重復計算 ++value 的遞增序列值填充範圍 [
first,
last)
。
等效操作(假設 ++value 返回遞增後的值)
*first = value; *++first = ++value; *++first = ++value; *++first = ++value; // repeats until “last” is reached
如果滿足以下任何條件,程式將不正確:
-
T
不能轉換為ForwardIt
的值型別。 - 表示式 ++val 格式錯誤,其中 val 是
T
型別的變數。
目錄 |
[編輯] 引數
first, last | - | 定義要用從 value 開始的遞增序列值填充的元素範圍的迭代器對 |
value | - | 要儲存的初始值 |
[編輯] 複雜度
恰好 std::distance(first, last) 次增量和賦值。
[編輯] 可能的實現
template<class ForwardIt, class T> constexpr // since C++20 void iota(ForwardIt first, ForwardIt last, T value) { for (; first != last; ++first, ++value) *first = value; } |
[編輯] 注意
此函式以程式語言 APL 中的整數函式 ⍳ 命名。它是STL 元件之一,未包含在 C++98 中,但在 C++11 中進入標準庫。
[編輯] 示例
以下示例將 std::shuffle 應用於 vector 的 std::list 迭代器。std::iota
用於填充容器。
執行此程式碼
#include <algorithm> #include <iomanip> #include <iostream> #include <list> #include <numeric> #include <random> #include <vector> class BigData // inefficient to copy { int data[1024]; /* some raw data */ public: explicit BigData(int i = 0) { data[0] = i; /* ... */ } operator int() const { return data[0]; } BigData& operator=(int i) { data[0] = i; return *this; } /* ... */ }; int main() { std::list<BigData> l(10); std::iota(l.begin(), l.end(), -4); std::vector<std::list<BigData>::iterator> v(l.size()); std::iota(v.begin(), v.end(), l.begin()); // Vector of iterators (to original data) is used to avoid expensive copying, // and because std::shuffle (below) cannot be applied to a std::list directly. std::shuffle(v.begin(), v.end(), std::mt19937{std::random_device{}()}); std::cout << "Original contents of the list l:\t"; for (const auto& n : l) std::cout << std::setw(2) << n << ' '; std::cout << '\n'; std::cout << "Contents of l, viewed via shuffled v:\t"; for (const auto i : v) std::cout << std::setw(2) << *i << ' '; std::cout << '\n'; }
可能的輸出
Original contents of the list l: -4 -3 -2 -1 0 1 2 3 4 5 Contents of l, viewed via shuffled v: -1 5 -4 0 2 1 4 -2 3 -3
[編輯] 另請參閱
(C++20) |
由重複遞增初始值生成的序列組成的 view (類模板) (自定義點物件) |
將給定值複製賦給一個範圍中的每個元素 (函式模板) | |
(C++20) |
給一個範圍的元素賦某個值 (演算法函式物件) |
將連續函式呼叫的結果賦給一個範圍中的每個元素 (函式模板) | |
(C++20) |
將一個函式的結果儲存在一個範圍中 (演算法函式物件) |
(C++23) |
以起始值的連續增量填充一個範圍 (演算法函式物件) |