C++ STL iota 使用方法

发布时间 2023-08-15 20:01:35作者: Pocker7

C++ STL iota用法

介绍

c++ 11 引入的函数,C++20后小更新 使用 #include<numeric> 头文件引用
功能
std::iota [aɪ'otə]输入一个值和一个容器的开始地址和结束地址,对该容器进行自增填充。

Example

点击查看代码
#include<numeric>
#include<vector>
using namespace std;
int main(){
  vector<int> arr(10);
  for ( int i = 0; i < arr.size(); i++ )
    cout<<arr[i]<<" ";
  cout<<endl;
  iota(arr.begin(), arr.end(), 42);
  for ( int i = 0; i < arr.size(); i++ )
    cout<<arr[i]<<" ";
  cout<<endl;
  
  return 0;
}

运行结果:

image

具体定义

// c++ 11
template< class ForwardIt, class T >
void iota( ForwardIt first, ForwardIt last, T value );

将first到last的区域填充为线性增加的value值,从value开始递增。相当于

*(first) = value;
*(first+1) = ++value;
*(first+2) = ++value;
...
// since c++ 20
template< class ForwardIt, class T >
constexpr void iota( ForwardIt first, ForwardIt last, T value );