STL基础学习笔记

  1. set
    set是实现红黑树的平衡二叉检索树的数据结构,插入元素时,它会自动调整二叉树的排列。
    set常用操作:
    begin(),返回set容器的第一个元素(*)
    end(),返回set容器的最后一个元素(*)//end()是指向最后一个元素的后一个位置
    clear(),删除set容器中的所有的元素
    empty(),判断set容器是否为空
    max_size(),返回set容器可能包含的元素最大个数
    size() ,返回当前set容器中的元素个数
    insert(),向set中插入某个元素
    lower_bound(x) ,返回第一个大于等于x的定位器位置(*)
    upper_bound(x),返回第一个大于x的定位器位置(*)
    find(),返回给定值值的定位器,如果没找到则返回end().

代码实现:

2 . map 与set操作基本类似,只是map类似与一个映射。查找的复杂度基本是Log(N)
常见:
begin() 返回指向map头部的迭代器
clear() 删除所有元素
count() 返回指定元素出现的次数
empty() 如果map为空则返回true
end() 返回指向map末尾的迭代器
erase() 删除一个元素
find() 查找一个元素
insert() 插入元素
lower_bound() 返回键值>=给定元素的第一个位置
max_size() 返回可以容纳的最大元素个数
size() 返回map中元素的个数
swap() 交换两个map(两个map中所有元素的实现)
upper_bound() 返回键值>给定元素的第一个位置

以上常见摘自http://www.cnblogs.com/fnlingnzb-learner/p/5833051.html
代码实现:

#include<iostream>
#include<map>
using namespace std;
map<int,string>h;
int main()
{
    h.insert(pair<int,string>(1,"ONE"));    //利用pair插入 
    h.insert(map<int, string>::value_type(2,"TWO"));    //利用value_type插入
    h[3]="THREE",h[4]="FOR"; //利用数组形式插入 ,可以覆盖原来的值
    map<int,string>::iterator it;
    for(it=h.begin();it!=h.end();it++)
    {
        if(it->first==1)
        cout<<it->first<<" "<<it->second<<endl;     
    }
    int nsize=h.size(); //当前已插入了多少元素 
    for(int i=1;i<=nsize;i++)
        cout<<h[i]<<" ";    
    it=h.find(1);
    if(it!=h.end()) cout<<"ok"<<endl;
    it=h.lower_bound(2), cout<<it->second<<endl;
    it=h.upper_bound(2),cout<<it->second<<endl;
    it=h.find(1);
    h.erase(it);//删除it指向的<int,string>
    it=h.lower_bound(1);
    cout<<endl<<it->second<<endl;
    it=h.upper_bound(1);
    cout<<endl<<it->second<<endl;    h.erase(h.begin(),h.end());//相当于h.clear(); 
    return 0;
}

3.string
因为考了个题,卡读入,贼恶心。需要用到string的奇怪姿势。
erase:
erase(p,n); 删除从p开始的n个字符(包括p这个位置开始)
erase(it);删除it这个位置的一个字符(it是个迭代器)
erase(sta,end);删除从sta到end之间的字符(sta和end都是迭代器)
删除后会自动调整位置。
find:
find函数的可用来做字符串的包含关系,如果字符串存在包含关系,返回值就是匹配的首字母在原串中的位置,否则会返回-1。
insert:
insert(it,’* * ‘)就是可以在it指向的这个位置插入一个单个字符* *,后面的会后移。
substr:
substr(pos,n)从第pos位开始,截取n位。

代码:

#include <iostream>
#include <string>
using namespace std;
string str ("where there is a will,there is a way.");
string::iterator it;
int main ()
{
    str.erase(0,1);
    cout<<str<<endl;
    it=str.begin()+6;
    str.erase (it);
    cout<<str<<endl;
    str.erase(str.begin()+6, str.end()-6);
    cout<<str<<endl;
    it=str.begin()+2;
    str.insert(it,'P');
    cout<<str<<endl;
    cout<<str.find("way.")<<endl;
    if(str.find("way.")==-1)    cout<<"no"<<endl;
    else    cout<<"yes"<<endl;
    if(str.find("hello ")==-1)  cout<<"no"<<endl;
    else    cout<<"yes"<<endl;
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值