栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

vector插入/删除元素

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

vector插入/删除元素

学习链接
插入元素

  • vector.insert(pos,elem); //在pos位置插入一个elem元素的拷贝,返回新数据的位置。

  • vector.insert(pos,n,elem); //在pos位置插入n个elem数据,无返回值。

  • vector.insert(pos,beg,end); //在pos位置插入[beg,end)区间的数据,无返回值 。

删除元素

  • vector.clear(); //移除容器的所有数据

  • vec.erase(beg,end); //删除[beg,end)区间的数据,返回下一个数据的位置。

  • vec.erase(pos); //删除pos位置的数据,返回下一个数据的位置。

#include 
#include 
using namespace std;

//输出函数
void co(string &a,vector &x){
    for(auto i : a){
        cout< a;
    vector b;
    for(int i = 0; i < 5; i++){
        a.push_back(i);
    }
    b.push_back(100);
    b.push_back(200);
    b.push_back(300);

    string  tag = "a";
    co(tag,a);
    tag = "b";
    co(tag,b);

    int n;
    a.insert(a.begin() + 2,600);
    tag = "a1";
    co(tag,a);

    for(int i = 0; i < a.size(); i++){
        cout<<"当前a大小为:"<::iterator it = a.erase(a.begin()+1);
    tag = "a3";
    co(tag,a);

    //测试迭代器是否指向下一个元素
    a.insert(it,2);
    tag = "a4";
    co(tag,a);

    a.erase(a.begin()+0,a.begin()+2);
    tag = "a5";
    co(tag,a);
    
}

输入结果:

/home/rock/CLionProjects/untitled/cmake-build-debug/untitled
a: [ 0 1 2 3 4 ]
b: [ 100 200 300 ]
a1: [ 0 1 600 2 3 4 ]
当前a大小为:6 
当前a大小为:5 
当前a大小为:4 
a2: [ 1 2 4 ]
a3: [ 1 4 ]
a4: [ 1 2 4 ]
a5: [ 4 ]

Process finished with exit code 0

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/690451.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号