当我们想对一个容器的值进行填充时,我们就可以使用
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
针对上面的输出,需要注意如下几点:
#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
。
如何使用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";
- 执行结果:
