STL之insert_iterator

insert_iterator功能:指定要插入容器的位置,然后向插入点后插入元素。如ListA{1,2,3,4,5,6,7,8,9} 。插入点位置在5处。要插入的链表为ListB{555,666,777}
,则结果为{1,2,3,4,5,555,666,777,6,7,8,9}。
  

     见以下例子

//advance(i, n) 指定迭代器i前进n步 相当于i=i+n

//http://www.cplusplus.com/reference/iterator/advance/
#include 
#include 
#include 
using namespace std;

void TestAdvance()
{
  list mylist;
  for (int i=0; i<10; i++) mylist.push_back (i*10);

  list::iterator it = mylist.begin();

  advance (it,5);

  cout << "The sixth element in mylist is: " << *it << endl;
}

//http://www.cplusplus.com/reference/iterator/inserter/
//输出A链表到B链表中 输出的位置由B链表迭代器的位置指定
//this function generates an insert iterator for a container.
//template
 // OutputIterator copy ( InputIterator first, InputIterator last, OutputIterator result )
//{
//  while (first!=last) *result++ = *first++;
//  return result;
//}

void TestCopyOutputIterator()
{
  list firstlist, secondlist;
  for (int i=1; i<=5; i++)
  { firstlist.push_back(i); secondlist.push_back(i*10); }

  list::iterator it;
  it = firstlist.begin(); advance (it,3);

  copy (secondlist.begin(),secondlist.end(),inserter(firstlist,it));

  for ( it = firstlist.begin(); it!= firstlist.end(); ++it )
	  cout << *it << " ";
  cout << endl;
}
/*
template 
  class insert_iterator :
    public iterator
{
protected:
  Container* container;
  typename Container::iterator iter;

public:
  typedef Container container_type;
  explicit insert_iterator (Container& x, typename Container::iterator i)
    : container(&x), iter(i) {}
  insert_iterator& operator= (typename Container::const_reference value)
    { iter=container->insert(iter,value); ++iter; return *this; }
  insert_iterator& operator* ()
    { return *this; }
  insert_iterator& operator++ ()
    { return *this; }
  insert_iterator operator++ (int)
    { return *this; }
};
*/
//还可以直接使用insert_iterator迭代器
void TestCopy()
{
	  list firstlist, secondlist;
  for (int i=1; i<=5; i++)
  { firstlist.push_back(i); secondlist.push_back(i*10); }

  list::iterator it;
  it = firstlist.begin(); advance (it,3);

  insert_iterator< list > insert_it (firstlist,it);

  copy (secondlist.begin(),secondlist.end(),insert_it);

  for ( it = firstlist.begin(); it!= firstlist.end(); ++it )
	  cout << *it << " ";
  cout << endl;
}

int main () {

	TestAdvance();
	TestCopyOutputIterator();
	TestCopy();
  return 0;
}


结果

The sixth element in mylist is: 50
1 2 3 10 20 30 40 50 4 5
1 2 3 10 20 30 40 50 4 5


 

你可能感兴趣的:(C++)