std::iota 定义于头文件 <numeric>,可用于按顺序递增填充[first, last)范围的值。我们只需要给出范围和填充的初始最小值即可。
函数原型
template< class ForwardIt, class T >
void iota( ForwardIt first, ForwardIt last, T value );
参数
- first, last - 以 value 开始,按顺序递增填充的值的范围
- value - 要存储的初始值,表达式 ++value 必须为良式
- 返回值
(无)
可能的实现方式:
template<class ForwardIterator, class T>
constexpr // C++20 起
void iota(ForwardIterator first, ForwardIterator last, T value)
{
while(first != last) {
*first++ = value;
++value;
}
}
std::iota 的 value参数是一个模板参数。因此我们可以对一个 list< int> 数组填充 0-n 的数据,也可以把一个 vector<list::iterator> 数组中填充上list的迭代器,如下实例所示:
#include <iostream>
#include <iterator>
#include <algorithm>
#include <numeric>
#include <list>
#include <vector>
int main()
{
// list填充
std::list<int> l(10);
std::iota(l.begin(), l.end(), 0); // 0 - 9
std::copy(l.begin(), l.end(), // 使用std::copy 输出
std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';
// vector中保存list的迭代器
std::vector<std::list<int>::iterator> v(l.size());
std::iota(v.begin(), v.end(), l.begin());
// 使用*i,输出vector中迭代器指向的值(即,list中的值)
for (auto i : v) std::cout << *i << ' ';
std::cout << '\n';
return 0;
}
// 输出
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
除此之外,我们也可以对我们的普通数组使用,进行快速初始化数据。
int main()
{
int arr[10];
std::iota(arr, arr+10, 10); // 10 - 19
for (int i : arr) std::cout << i << ' ';
std::cout << '\n';
// 输出 10 11 12 13 14 15 16 17 18 19
return 0;
}