命名空间
变体
操作

std::iota

来自 cppreference.cn
< 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
(类模板) (自定义点对象)[编辑]
将给定值复制赋给一个范围中的每个元素
(函数模板) [编辑]
给一个范围的元素赋某个值
(算法函数对象)[编辑]
将连续函数调用的结果赋给一个范围中的每个元素
(函数模板) [编辑]
将一个函数的结果保存在一个范围中
(算法函数对象)[编辑]
以起始值的连续增量填充一个范围
(算法函数对象)[编辑]