C++学习 fill和fill_n和for_each()函数的应用

本文详细介绍了C++中fill和fill_n函数的使用方法及应用场景,通过实例代码展示了如何通过这些函数实现数组元素的批量赋值。文章还提供了函数的详细解释和例子,帮助读者理解并应用这些功能。

C++学习 fill和fill_n函数的应用

fill函数的作用是:将一个区间的元素都赋予val值。函数参数:fill(first,last,val);//first为容器的首迭代器,last为容器的末迭代器,val为将要替换的值。

例题:给你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;
}
对for_each(V.begin(),V.end(),paint);的解释:
for_each()事实上是个function template(模板函数),其實做如下[effective STL item 41]
 
template<typename InputIterator, typename Function>
Function for_each(InputIterator beg, InputIterator end, Function f) {
  while(beg != end) 
    f(*beg++);
}



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 20 33 33 33 10 10
        cout << "myvector contains:";
        for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
              cout << " " << *it;
         cout << endl;
 return 0;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值