back_insert_iterator

 转自: http://www.cplusplus.com/reference/std/iterator/back_insert_iterator/

back_insert_iterator

<iterator>
template <class Container> class back_insert_iterator;
Back insert iterator

Back insert iterators are a special output iterator class designed to allow algorithms that usually overwrite elements (such as copy) to instead insert new elements at the end of the container.

The container must have member push_back defined (such as standard containersvector,deque and list).

Using the assignment operator on the back_insert_iterator, even when dereferenced, causes the container to append a new element to it. The other typical operators of anoutput iterator are also defined forback_insert_iterator but have no effect.

It is defined with an identical operation to:

template <class Container>
  class back_insert_iterator :
    public iterator<output_iterator_tag,void,void,void,void>
{
protected:
  Container* container;

public:
  typedef Container container_type;
  explicit back_insert_iterator (Container& x) : container(x) {}
  back_insert_iterator<Container>& operator= (typename Container::const_reference value)
    { container->push_back(value); return *this; }
  back_insert_iterator<Container>& operator* ()
    { return *this; }
  back_insert_iterator<Container>& operator++ ()
    { return *this; }
  back_insert_iterator<Container> operator++ (int)
    { return *this; }
};

 The library provides a function, called back_inserter, that automatically generates a back_insert_iterator class from a container.

template<typename InputIterator,typename InputIterator,typename OutputIterator>OutputIterator copy	
	(InputIterator first,InputIterator last,OutputInterator x{
                for(;first!=last;++x,++first)*x=*first;
                return(x);
        } 


Member functions

constructor
back_insert_iterator objects are constructed from a container.
operator=
Inserts a new element in the container, initializing its value to a copy of the argument.
operator*
Does nothing. Returns a reference to the object.
operator++
Does nothing. Returns a reference to the object.

Example 

// back_insert_iterator example
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;

int main () {
  vector<int> firstvector, secondvector;
  for (int i=1; i<=5; i++)
  { firstvector.push_back(i); secondvector.push_back(i*10); }

  back_insert_iterator< vector<int> > back_it (firstvector);

  copy (secondvector.begin(),secondvector.end(),back_it);

  vector<int>::iterator it;
  for ( it = firstvector.begin(); it!= firstvector.end(); ++it )
	  cout << *it << " ";
  cout << endl;

  return 0;
}


Output:

1 2 3 4 5 10 20 30 40 50
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值