相关文章推荐

当我们想对一个容器的值进行填充时,我们就可以使用 fill() 函数。

Fill range with value
Assigns val to all the elements in the range [first,last).

2.怎么用 fill() ? 2.1 使用 fill() 函数填充普通一维数组
  • 代码如下:
#include <iostream>     // std::cout
#include <algorithm>    // std::fill
using namespace std;
int main () {
  int array[8];                       // myvector: 0 0 0 0 0 0 0 0
  cout<<"=======begin======="<<"\n"; 
  for (int i = 0;i< 8;i++)
    cout << ' ' << array[i];
  cout << '\n'<<'\n';
  fill (array,array+4,5);   // myvector: 5 5 5 5 0 0 0 0
  fill (array+3,array+6,8);   // myvector: 5 5 5 8 8 8 0 0
  cout<<"=======after fill======="<<"\n"; 
  for (int i = 0;i< 8;i++)
    cout << ' ' << array[i];
  cout << '\n'<<'\n';
  return 0;
  • 执行结果:
=======begin=======
 -1 -1 4253733 0 1 0 4254665 0
=======after fill=======
 5 5 5 8 8 8 4254665 0

针对上面的输出,需要注意如下几点:

 
推荐文章