在C++中,iota是一个算法函数,定义在头文件 <numeric> 中,用于生成一个连续递增的序列。
函数签名如下:
template<class ForwardIt, class T>
void iota(ForwardIt first, ForwardIt last, T value);
iota函数接受两个迭代器 first 和 last,以及一个初始值 value。它会从 first 开始,逐个增加值,并将递增的值赋给范围内的元素,直到 last(不包括 last)。
下面是一个使用 iota 函数生成连续递增序列的示例:
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> numbers(5);
int startValue = 1;
std::iota(numbers.begin(), numbers.end(), startValue);
for (const auto& num : numbers) {
std::cout << num << " ";
}
return 0;
}
输出:
1 2 3 4 5
在上述示例中,我们使用 iota 函数将初始值 startValue(为1)赋给了 numbers 容器中的元素,每个元素的值逐个递增。这样就生成了一个连续递增的序列。