即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

iterator adapter inserter

编程语言 INGNIGHT 12℃ 0评论
本文目录
[隐藏]

1.1.insert_iterator

这个adapter将iterator的赋值(assign)操作变为安插(insert操作),并将iterator右移一个位置。如此便可让user连续执行[表面上assign而实际上insert]的行为。

template


class insert_iterator {


protected:


  _Container* container; //底层容器


  typename _Container::iterator iter;


public:


  typedef _Container          container_type;


  typedef output_iterator_tag iterator_category;//注意类型


  typedef void                value_type;


  typedef void                difference_type;


  typedef void                pointer;


  typedef void                reference;





  insert_iterator(_Container& __x, typename _Container::iterator__i)


    : container(&__x),iter(__i) {}


  insert_iterator<_Container>&


  operator=(const typename _Container::value_type& __value) {


    iter = container->insert(iter, __value); //关键:转调用insert()


    ++iter//令insert_iterator永远跟随其target贴身移动


    return *this;


  }


  insert_iterator<_Container>& operator*() { return *this; }


  insert_iterator<_Container>& operator++() { return *this; }


  insert_iterator<_Container>& operator++(int) { return *this; }

};

2.2.inserter

辅助函式,帮助user使用inserter_iterator

template


inline


insert_iterator<_Container> inserter(_Container&__x, _Iterator__i)


{


  typedef typename _Container::iterator __iter;


  return insert_iterator<_Container>(__x, __iter(__i));


}

3.3.copy

template

             class OutputIterator>

OutputIterator

          copy(InputIterator first,InputIterator last,OutputIterator
result
)

{

              while(first != last) {

                      *result = *first;

                      ++result ; ++first;

               }

               return result;

}

4.4.示例

http://www.cplusplus.com/reference/iterator/inserter/



// inserter example
#include      // std::cout
#include      // std::front_inserter
#include          // std::list
#include     // std::copy

int main () {
  std::list foo,bar;
  for (int i=1; i<=5; i++)
  { foo.push_back(i); bar.push_back(i*10); }

  std::list::iterator it = foo.begin();
  advance (it,3);
  std::cout << "foo contains:";
  for ( std::list::iterator it = foo.begin(); it!= foo.end(); ++it )
   std::cout << ' ' << *it;
  std::cout << '\n';
  
  std::cout << "bar contains:";
  for ( std::list::iterator it = bar.begin(); it!= bar.end(); ++it )
   std::cout << ' ' << *it;
  std::cout << '\n';

  std::copy (bar.begin(),bar.end(),std::inserter(foo,it));


  std::cout << "foo contains:";
  for ( std::list::iterator it = foo.begin(); it!= foo.end(); ++it )
   std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}



执行结果:



            

转载请注明:CodingBlog » iterator adapter inserter

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情