C++语法基础--泛型算法(generic algorithm)--写入容器元素的算法fill(),fill_n,replace()

*fill
 Assigns val to all the elements in the range [first,last)
 原型:
  template <class ForwardIterator, class T>
  void fill (ForwardIterator first, ForwardIterator last, const T& val);

 该算法等效于:
  template <class ForwardIterator, class T>
  void fill (ForwardIterator first, ForwardIterator last, const T& val)
{
  while (first != last) {
    *first = val;
    ++first;
  }
}



 Example:
int main ()
 {
  vector<int> myvector (8);                      
// myvector: 0 0 0 0 0 0 0 0
  fill (myvector.begin(),myvector.begin()+4,1);   // myvector: 1 1 1 1 0 0 0 0
  fill (myvector.begin()+3,myvector.end()-2,2);   // myvector: 1 1 1 2 2 2 0 0

 

  //myvector contains:

  for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
  {
  cout << ' ' << *it;//  1 1 1 2 2 2 0 0
  }
  
   return 0;
}




*fill_n

 Assigns val to the first n elements of the sequence pointed by first.

原型:

 template <class OutputIterator, class Size, class T>
  void fill_n (OutputIterator first, Size n, const T& val);

该算法等效于:
 template <class OutputIterator, class Size, class T>
  OutputIterator fill_n (OutputIterator first, Size n, const T& val)
{
  while (n>0) {
    *first = val;
    ++first; --n;
  }
  return first;     // since C++11
}


 Example:
  int main () 
 {
  vector<int> myvector (8,1);      
 // myvector: 1 1 1 1 1 1 1 1
  std::fill_n (myvector.begin(),4,2);     // myvector: 2 2 2 2 1 1 1 1
  
  //myvector contains:
  for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
  {
  cout << ' ' << *it;//2 2 2 2 1 1 1 1
  }

   return 0;
}

 
 Tips:
   fill_n假定对指定数量的元素做写操作时是安全的,所以要确保容器有足够的空间。




*replace
 Assigns new_value to all the elements in the range [first,last) that compare equal to old_value.
 原型:
  template <class ForwardIterator, class T>
  void replace (ForwardIterator first, ForwardIterator last,
                const T& old_value, const T& new_value);

 该算法等效于:
 template <class ForwardIterator, class T>
  void replace (ForwardIterator first, ForwardIterator last,
                const T& old_value, const T& new_value)
{
  while (first!=last) {
    if (*first == old_value) *first=new_value;
    ++first;
  }
}



Example:
int main ()
 {
  int myints[] = { 1,1,1,3,2,2,1,3 };
  vector<int> myvector (myints, myints+8);  
// 1,1,1,3,2,2,1,3 

 

  replace (myvector.begin(), myvector.end(), 3, 2);// 1,1,1,2,2,2,1,2


    //myvector contains:
  for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
  {
  cout << ' ' << *it;// 1,1,1,2,2,2,1,2
  }
 
   return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值