0
点赞
收藏
分享

微信扫一扫

C++ 中 fill() 的使用

爱动漫建模 2022-01-26 阅读 67


​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";
}
}
  • 执行结果:
    C++ 中 fill() 的使用_#include

参考文章

  • ​​http://www.cplusplus.com/reference/algorithm/fill/​​


举报

相关推荐

0 条评论