C++学习笔记25——泛型算法之写入容器

1,fill函数

template< class ForwardIt, class T >
void fill( ForwardIt first, ForwardIt last, const T& value );

效果:将[first, last)范围内的每个元素都设为value.


2,fill_n函数

template< class OutputIt, class Size, class T >
void fill_n( OutputIt first, Size count, const T& value );        // (until C++11)

template< class OutputIt, class Size, class T >
OutputIt fill_n( OutputIt first, Size count, const T& value );	  // (since C++11)
效果:从first开始将count个元素的值设为value.

返回值:C++ 11之前,返回void
                C++ 11之后,返回赋值的最后一个元素的下一个位置的迭代器,count为0时返回first

注意:fill_n总是假定容器足够大,可以放下count个元素。但前面已经提到,算法本身是不会改变容器大小的,所以fill_n函数不会为容器开辟空间。当容器不够大时会发生运行时错误。最常见的出错类型在一个刚定义的空容器上调用fill_n:
vector<int> ivec; //空容器
fill_n(ivec.begin(), 10, 0); // !!!Error!

3,copy函数

template< class InputIt, class OutputIt >
OutputIt copy( InputIt first, InputIt last, OutputIt d_first );
效果:将[first, last)之间的元素copy到从d_first开始的元素中去。

类似于容器操作assign(b, e)
应该同样需要小心目标容器的大小是否足够容纳要写入的元素。

4,插入迭代器(insert iterator)

插入迭代器:可以给基础容器添加元素的迭代器。
用迭代器给容器元素赋值时,被赋值的是迭代器所指向的元素。而使用插入迭代器时,则会在容器中添加一个新元素。

5,back_inserter函数

头文件:
#include<iterator>
template< class Container >
std::back_insert_iterator<Container> back_inserter( Container& c );

back_inserter  is a convenience function template that constructs a  std::back_insert_iterator  for the container  c with the type deduced from the type of the argument.
back_inserter函数时迭代器适配器,其实参是一个容器的引用,返回一个绑定在该容器上的插入迭代器。
当用这个迭代器给元素赋值时,赋值运算将调用push_back()在容器中添加元素。

所以可以联合使用fill_n和back_inserter给空容器赋值:
vector<int> ivec; //空容器
fill_n(back_inserter(ivec), 10, 0); //OK.向ivec中追加10个元素

也可以将copy与back_inserter联合使用:
vector<int> ivec;
list<int> iList(10,1);
copy(ivec.begin(), ivec.end(), back_inserter(ivec));

6,replace函数

template< class ForwardIt, class T >
void replace( ForwardIt first, ForwardIt last,
              const T& old_value, const T& new_value );	

template< class ForwardIt, class UnaryPredicate, class T >
void replace_if( ForwardIt first, ForwardIt last,
                 UnaryPredicate p, const T& new_value );
谓词p的原型为: bool pred(const Type &a);
效果:将[first, last)范围内所有满足条件的元素替换为 new_value
     无谓词的第一个版本,将范围内值为old_value的元素替换掉;
     有谓词的第二个版本,将范围内使谓词p返回true的元素替换掉。

7,replace_copy函数

template< class InputIt, class OutputIt, class T >
OutputIt replace_copy( InputIt first, InputIt last, OutputIt d_first,
                       const T& old_value, const T& new_value );
	
template< class InputIt, class OutputIt, class UnaryPredicate, class T >
OutputIt replace_copy_if( InputIt first, InputIt last, OutputIt d_first,
                          UnaryPredicate p, const T& new_value );
谓词p的原型为:   bool  pred ( const  Type  & a ) ;
效果:与replace类似,只是不改变原来的序列,将替换后的序列到存到从 d_first开始的容器中。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值