C++ STL库的基本用法

本文介绍了C++中的几种常用数据结构,包括vector的一维数组操作、set自动排序和插入删除、queue先进先出特性、priority_queue(大根堆和小根堆)以及map和unordered_map的插入和遍历。
摘要由CSDN通过智能技术生成

目录

vector

set

queue

priority_queue(堆)优先队列

大根堆

小根堆

map unordered_map


vector
vector<int> heap;//一维数组 
for(int i=1;i<=10;i++){
    heap.push_back(i);
}
heap.push_back();//元素插入尾部 
heap.pop_back();//弹出尾部元素 
heap.empty();// 判断是否为空 
cout<<heap.size()<<endl;//10  返回数组长度 
heap.erase()//{删除单个元素下标 ||删除区间 [i,j) }
for(auto it: heap){//1 2 3 4 5 6 7 8 9 10 遍历数组 
    cout<<it<<" ";
}
cout<<endl<<heap.front()<<" "<<heap.back();
set

自带排序从小到大

set<int> heap;
for(int i=1;i<=10;i++){
    heap.insert(i);
}
//  heap.insert();//元素插入尾部 
//  heap.clear();//元素 
//  heap.find();
//heap.erase()//{删除单个元素值或者find()函数返回的迭代器也行 ||删除区间 [i,j(heap.end())] }
cout<<heap.size()<<endl;//10  返回长度 
for(auto it: heap){//1 2 3 4 5 6 7 8 9 10 遍历
    cout<<it<<" ";
}
cout<<endl<<*heap.find(7);
//7 因为find()函数返回的是指针,所以加*是取值 

queue
queue<int> heap;
for(int i=10;i>=1;i--){
    heap.push(i);//尾部插入元素
}
//  heap.pop();//弹出队头元素
cout<<heap.front()<<endl;//返回队头元素
cout<<heap.back()<<endl;//返回队尾元素
cout<<heap.size()<<endl;//10  返回长度 
while(heap.size()){//遍历
    cout<<heap.front()<<" ";
    heap.pop();
}

priority_queue(堆)优先队列
大根堆

默认大根堆

    priority_queue<int> heap;
    for(int i=10;i>=1;i--){
        heap.push(i);
    }
//  heap.pop();
    cout<<heap.top()<<endl;
    cout<<heap.size()<<endl;//10  返回长度 
    while(heap.size()){
        cout<<heap.top()<<" ";
        heap.pop();
    }

小根堆
priority_queue<int,vector<int>,greater<int>> heap;
    for(int i=10;i>=1;i--){
        heap.push(i);
    }
//  heap.pop();
    cout<<heap.top()<<endl;
    cout<<heap.size()<<endl;//10  返回长度 
    while(heap.size()){
        cout<<heap.top()<<" ";
        heap.pop();
    }

map unordered_map
    map<int,int> heap;  
    unordered_map<int,int> heap;
    for(int i=10;i>=1;i--){
        heap.insert({i,i+1});
    }
    cout<<heap.size()<<endl;//10  返回长度 
    for(auto it: heap){//遍历
        cout<<it.first<<" "<<it.second<<endl;
    }

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值