std::iota() 算法
- 自 C++20 起
- 自 C++11 起
// (1)
template< class ForwardIt, class T >
constexpr void iota( ForwardIt first, ForwardIt last, T value );
// (1)
template< class ForwardIt, class T >
void iota( ForwardIt first, ForwardIt last, T value );
使用从 value
开始并重复计算 ++value
的递增序列值填充范围 [first
; last
)。
等效操作
*(first) = value;
*(first + 1) = ++value;
*(first + 2) = ++value;
*(first + 3) = ++value;
...
参数
first second | 要填充从 |
值 | 要存储的初始值。 |
类型要求
++value | 必须格式正确。 |
返回值
(无)
复杂度
精确地 last - first
次递增和赋值。
异常
(无)
可能的实现
iota(1)
template<class ForwardIt, class T>
constexpr // since C++20
void iota(ForwardIt first, ForwardIt last, T value)
{
while (first != last)
{
*first++ = value;
++value;
}
}
备注
该函数以编程语言 APL 中的整数函数 ⍳
命名。它是 C++98 中未包含但进入 C++11 标准库的 STL 组件之一。
示例
Main.cpp
#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 (auto const& n : l) std::cout << std::setw(2) << n << ' ';
std::cout << '\n';
std::cout << "Contents of l, viewed via shuffled v:\t";
for (auto const 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