![C++学习fill和fill_n函数的应用_glp](http://img.aihuau.com/images/01111101/01030248t013cc13fdb97c3f90f.png)
例题:给你n个数,然后输入一些操作:start,end,paint。表示从start到end都赋予paint的值,并输出每一次操作后的数组状态。代码:#include<iostream>#include<algorithm>#include<vector>using namespace std;void print(int&elem){cout<<elem<<"";}int main(){ vector <int>V; int n,startpos,endpos,paint; cin>>n; V.resize(n);while(cin>>startpos>>endpos>>paint) { fill(V.begin()+startpos-1,V.begin()+endpos,paint); for_each(V.begin(),V.end(),print); cout<<endl; } return 0;}fill_n函数的作用是:给你一个起始点,然后再给你一个数值count和val。把从起始点开始依次赋予count个元素val的值。注意: 不能在没有元素的空容器上调用fill_n函数例题:给你n个数,然后输入一些操作:start,count,paint。表示从start开始连续填充count个数字,paint为填充的数值。代码:#include<iostream>#include<algorithm>#include<vector>using namespace std;void print(int&elem){cout<<elem<<"";}int main(){ vector <int>V; int n,start,count,paint; cin>>n; V.resize(n);while(cin>>start>>count>>paint) { fill_n(V.begin()+start-1,count,paint); for_each(V.begin(),V.end(),print); cout<<endl; } return 0;}再发一下关于fill_n函数的例子:// fill_n example#include<iostream>#include<algorithm>#include<vector>using namespace std;
int main () {vector<int> myvector (8,10); // myvector: 10 10 10 10 10 10 10 10
fill_n(myvector.begin(),4,20); //myvector: 20 20 20 20 10 10 10 10 fill_n(myvector.begin()+3,3,33); // myvector: 20 20 2033 33 33 10 10
cout<< "myvector contains:"; for(vector<int>::iteratorit=myvector.begin(); it!=myvector.end(); ++it) cout << " "<< *it;
cout<< endl; return0;}