zoukankan      html  css  js  c++  java
  • vector insert()

    1. 语法:

    vector_name.insert (position, val)

    - position:插入的位置;

    - val:插入的值;

    Return value:返回一个迭代器Iterator,指向新插入的元素。

    // program below illustrates the 
    // vector::insert() function 
    
    #include <bits/stdc++.h> 
    using namespace std; 
    
    int main() 
    { 
        // initialising the vector 
        vector<int> vec = { 10, 20, 30, 40 }; 
    
        // inserts 3 at front 
        auto it = vec.insert(vec.begin(), 3); 
        
        // inserts 2 at front 
        vec.insert(it, 2); 
    
        cout << "The vector elements are: "; 
        for (auto it = vec.begin(); it != vec.end(); ++it) 
            cout << *it << " "; 
    
        return 0; 
    } 

    Output:

    The vector elements are: 2 3 10 20 30 40

    2. 语法:

    vector_name.insert(position, size, val)

    - position:插入的位置;

    - val:插入的值;

    - size:插入值的个数;

    Return value:返回一个迭代器Iterator,指向新插入的元素。

    // program below illustrates the 
    // vector::insert() function 
    
    #include <bits/stdc++.h> 
    using namespace std; 
    
    int main() 
    { 
        // initialising the vector 
        vector<int> vec = { 10, 20, 30, 40 }; 
    
        // inserts 3 one time at front 
        auto it = vec.insert(vec.begin(), 1, 3); 
        
        // inserts 4 two times at front 
        vec.insert(it, 2, 4); 
    
        cout << "The vector elements are: "; 
        for (auto it = vec.begin(); it != vec.end(); ++it) 
            cout << *it << " "; 
    
        return 0; 
    } 

    Output:

    The vector elements are: 4 4 3 10 20 30 40

    3. 语法:

    vector_name.insert(position, iterator1 , iterator2)

    - position:插入的位置;

    - iterator1 :插入元素的开始位置;

    - iterator2 :插入元素的结束位置;

    Return value:返回一个迭代器Iterator,指向新插入的元素。

    // program below illustrates the 
    // vector::insert() function 
    
    #include <bits/stdc++.h> 
    using namespace std; 
    
    int main() 
    { 
        // initialising the vector 
        vector<int> vec1 = { 10, 20, 30, 40 }; 
        vector<int>vec2; 
        
        // inserts at the beginning of vec2 
        vec2.insert(vec2.begin(),vec1.begin(),vec1.end()); 
    
        
        cout << "The vector2 elements are: "; 
        for (auto it = vec2.begin(); it != vec2.end(); ++it) 
            cout << *it << " "; 
    
        return 0; 
    } 

    参考链接:https://www.geeksforgeeks.org/vector-insert-function-in-c-stl/

  • 相关阅读:
    01_Linux基础篇
    Docker
    Day02_IP地址详解&进制转换&DOS基本命令与批处理
    Day01_虚拟化架构与系统部署
    重学TCP/IP协议和三次握手四次挥手
    作为一个程序员,CPU的这些硬核知识你必须会!
    通过docker-compose制作dubbo-admin和zookeeper组合服务
    双主master-master复制Err 1677故障分析
    唐宇迪-人工智能学习路线(上篇)
    DNS访问原理只需9个步骤
  • 原文地址:https://www.cnblogs.com/Bella2017/p/11331387.html
Copyright © 2011-2022 走看看