vector的insert方法详解

来源:互联网 发布:手机抢拍软件 编辑:程序博客网 时间:2024/05/16 05:37
cpp] view plaincopyprint?
  1. iterator insert(  
  2.    const_iterator _Where,  
  3.    const Type& _Val  
  4. );  
  5. iterator insert(  
  6.    const_iterator _Where,  
  7.    Type&& _Val  
  8. );  
  9. void insert(  
  10.    const_iterator _Where,  
  11.    size_type _Count,  
  12.    const Type& _Val  
  13. );  
  14. template<class InputIterator>  
  15.    void insert(  
  16.       const_iterator _Where,  
  17.       InputIterator _First,  
  18.       InputIterator _Last  
  19.    );  
例子:
[cpp] view plaincopyprint?
  1. void test_vector_insert()  
  2. {   
  3.     std::vector<int> v1;  
  4.     v1.push_back(10);  
  5.     v1.push_back(20);  
  6.     v1.push_back(30);  
  7.   
  8.     std::cout << "v1 = " ;  
  9.     std::copy(v1.begin(), v1.end(), std::ostream_iterator<int>(std::cout, " "));  
  10.     std::cout << std::endl;  
  11.   
  12.     // 方法1:   
  13.     v1.insert(v1.begin() + 1, 40);  
  14.     std::cout << "v1 = ";  
  15.     std::copy(v1.begin(), v1.end(), std::ostream_iterator<int>(std::cout, " "));  
  16.     std::cout << std::endl;  
  17.   
  18.     // 方法3:  
  19.     v1.insert(v1.begin() + 2, 4, 50);  
  20.     std::cout << "v1 = ";  
  21.     std::copy(v1.begin(), v1.end(), std::ostream_iterator<int>(std::cout, " "));  
  22.     std::cout << std::endl;  
  23.   
  24.     // 方法4:  
  25.     v1.insert(v1.begin() + 1, v1.begin() + 2, v1.begin() + 4);  
  26.     std::cout << "v1 = ";  
  27.     std::copy(v1.begin(), v1.end(), std::ostream_iterator<int>(std::cout, " "));  
  28.     std::cout << std::endl;  
  29. }  
0 0
原创粉丝点击