c++算法训练—(一)STL库

本文深入探讨了C++ STL库,包括pair的使用、vector的访问和操作、set与map的数据组织、队列的基本操作、priority_queue的自动排序以及stack的先进后出特性。通过实例讲解了各容器的特性和常见操作。
摘要由CSDN通过智能技术生成

1、STL算法库(c++特性)

pair(二元组、元素对)

位于头文件< iostream>中用来表示一个二元组或元素对
1.1 使用pair
定义一个pair对象表示一个平面面坐标点:

pair<double, double> p;
cin >> p.first >> p.second;

2.1排序

int cmp(pair<int,int > a,pair<int ,int > b){
   
	return a.second<b.second;
}

vector( 类数组 )

vector包含着一系列连续存储的元素,性质和数组十分相似。
访问元素或者在末尾插入元素常数级别,插入元素是线性级别。

要注意的是,vector的尾部元素是

vector<int> ve;
vector<int>::iterator::iter;
iter=ve.end()-1;    //这里一定要减
cout<*ite<<endl;

2.vector的操作

cvec.begin();    //返回第一个元素的迭代器 
vec.end();
vect.empty();
vec.front();    //返回第一个元素
vec.push_back();    //在最后添加一个元素
vec.pop_back();     //移除最后一个元素 

#include<bits/stdc++.h>
using namespace std;

vector<int> vec
int main(){
   
    vec.push_back(1);       //尾部插入元素
    vec.push_back(2);
    vec.push_back(5);
    
    //迭代器
vector<int>::iterator ite;
for(ite=vec.begin();ite!=vec.end();++ite){
   
    cout<<*ite<<endl;
} 

//插入元素,在第i+1个元素前面插入a 
vec.insert(vec.begin()+i,a); 
//删除元素
vec.erase(vec.begin()+2);  //删除第三个元素 

vec.size();
vec.clear();

return 0;
}

//vector的元素还可以是结构体,但是结构体一定要定义为全局 
#include<bits/stdc++.h>
using namespace std;
typedef struct rect{
   
    int id,length,width;
    //对于向量元素是结构体的,可以在结构体内部定义比较函数
    bool operator< (const rect &a)  const
    {
   
        if(id!=a.id)
            return id<a.id;
        else
        {
   
            if(length!=a.length)
                return length<a.length;
            else
                return width<a.width;
        }
    }
}Rect;
int main(){
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值