C++fill()的使用

1.什么是fill()?

当我们想对一个容器的值进行填充时,我们就可以使用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

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

  • 可以看到这里的输出有4254665这样的值,其原因是:我们没有对数组 array 进行初始化,所以导致出现这个怪异值。但是这不妨碍对fill()的使用验证。
  • 在使用数组 array 时,array代表的就是array[]的起始地址,而array+4代表的就是在起始向后偏移4个位置的元素。 所以:fill (array,array+4,5); 得到的结果就是array[0] = array[1] = array[2] = array[3] = 5。后面的操作同理,不再叙述。
2.2 使用fill()函数填充vector
  • 代码
#include <iostream>     // std::cout
#include <algorithm>    // std::fill
#include <vector>       // std::vector

using namespace std;

int main () {
  vector<int> myvector (8);                       // myvector: 0 0 0 0 0 0 0 0

	cout<<"=======begin======="<<"\n"; 
  for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    cout << ' ' << *it;
  cout << '\n'<<'\n';

  fill (myvector.begin(),myvector.begin()+4,5);   // myvector: 5 5 5 5 0 0 0 0
  fill (myvector.begin()+3,myvector.end()-2,8);   // myvector: 5 5 5 8 8 8 0 0

  cout<<"=======after fill======="<<"\n"; 
  for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    cout << ' ' << *it;
  cout << '\n';
  
  return 0;
}
  • 执行结果
=======begin=======
 0 0 0 0 0 0 0 0

=======after fill=======
 5 5 5 8 8 8 0 0

需要注意的地方

  • 因为vector不再是普通的数组了(即使它可以被视作是一个数组),所以我们不需要使用数组首地址的方式,因为vector已经给我们封装好了方法,其初始地址就是vector.begin(),末位地址就是vector.end()。其余同array
2.3 使用fill()函数填充二维数组

如何使用fill()函数填充二维数组呢?

  • 简要代码:
#include<cstdio>
#include<iostream>
using namespace std;

int main(){
	int G[6][4];
	fill(G[0],G[0]+6*4,520);
	for(int i = 0;i < 6;i++)
	{
		for(int j = 0;j < 4;j++){
			cout <<G[i][j] <<" ";
		}cout <<"\n";
	}
}
  • 执行结果:
    在这里插入图片描述
参考文章
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐