名稱空間
變體
操作

std::iota

來自 cppreference.com
< cpp‎ | 演算法
 
 
演算法庫
有約束演算法與針對範圍的演算法 (C++20)
有約束的演算法,例如 ranges::copyranges::sort 等……
執行策略 (C++17)
排序及相關操作
劃分操作
排序操作
二分搜尋操作
(於已劃分範圍上)
集合操作(於已排序範圍上)
歸併操作(於已排序範圍上)
堆操作
最小/最大值操作
(C++11)
(C++17)
字典序比較操作
排列操作
C 庫
數值操作
未初始化記憶體上的操作
 
 
定義於標頭檔案 <numeric>
template< class ForwardIt, class T >
void iota( ForwardIt first, ForwardIt last, T value );
(C++11 起)
(C++20 起為 constexpr)

用從 value 開始並重復計算 ++value 的遞增序列值填充範圍 [firstlast)

等效操作(假設 ++value 返回遞增後的值)

*first   = value;
*++first = ++value;
*++first = ++value;
*++first = ++value;
// repeats until “last” is reached

如果滿足以下任何條件,程式將不正確:

  • T 不能轉換為 ForwardIt值型別
  • 表示式 ++val 格式錯誤,其中 valT 型別的變數。

目錄

[編輯] 引數

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 應用於 vectorstd::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

[編輯] 另請參閱

由重複遞增初始值生成的序列組成的 view
(類模板) (自定義點物件)[編輯]
將給定值複製賦給一個範圍中的每個元素
(函式模板) [編輯]
給一個範圍的元素賦某個值
(演算法函式物件)[編輯]
將連續函式呼叫的結果賦給一個範圍中的每個元素
(函式模板) [編輯]
將一個函式的結果儲存在一個範圍中
(演算法函式物件)[編輯]
以起始值的連續增量填充一個範圍
(演算法函式物件)[編輯]