C++语法基础--泛型算法(generic algorithm)--插入迭代器back_inserter(),front_insertor(),inserter()以及next()函数简介

   今天研究迭代器时发现原来for循环可以这样写:
     
     int my_array[5] = {1, 2, 3, 4, 5};  
     for (int &x : my_array)  
    {  
          cout<      }  

   百度了一下才知道:C++11支持以范围为基础的 for 循环。看来又要多花点时间去掌握C++11的新特性了。




1.标准库所定义的迭代器不依赖于特定的容器,事实上C++还提供了另外三种迭代器:
  *插入迭代器
  *iostream迭代器
  *反向迭代器


2.C++提供三种插入器
  *back_inserter:使用push_back实现插入的迭代器
    Constructs a back-insert iterator that inserts new elements at the end of x.
   
   原型:
    template
  back_insert_iterator back_inserter (Container& x);

  
  解析:
    x  :
        Container on which the iterator will insert new elements.
        Container should be a container class with member push_back defined.
   return:
        A back_insert_iterator that inserts elements at the end of container x.


  Example:
   int main()
{
int arr[]={1,2,3};
        vector vec(arr,arr+3);
       fill_n(back_inserter(vec), 3, -1);
      for (int n : vec)

        {

          cout << n << ' ';

         }

}


//output://1 2 3 -1 -1 -1




  *front_inserter:使用push_front实现插入
   类似于back_inserter,这里就不举例了


  *inserter: 使用insert实现插入
   Constructs an insert iterator that inserts new elements int x at the position pointed by it.
 
  原型:
   template< class Container >
    std::insert_iterator inserter( Container& c, typename Container::iterator i );



 Example:
    
int main()
{
int arr[]={1,2,3,4,5};
    list lst(arr,arr+5);
    fill_n(inserter(lst, next(lst.begin(),2)), 3, -1);
   
    for (int n : lst)
{
        cout << n << ' ';
    }
   
 }



Output:1 2 -1 -1 -1 3 4 5
 
  






3.next()
  Returns an iterator pointing to the element that it would be pointing to if advanced n positions.
  原型:
   template
    ForwardIterator next (ForwardIterator it,
                           typename iterator_traits::difference_type n = 1);

  解析:
   it :  an iterator
    n    : number of elements to advance
  Return :The nth successor of iterator it.

  Example:
    int main() 
{
int arr[]={1,2,3,4};
vector v(arr,arr+4);
        vector::iterator it = v.begin();
      vector::iterator  nx = std::next(it, 2);
      cout << *it << ' ' << *nx << '\n';
//1 3
}

你可能感兴趣的:(c++语法基础总结笔记)