STL

STL

vector

  • 动态数组

操作:

//定义
vector<int> v;
//清空
v.clear();
//添加到末尾
v.push_back(a);
//删除
v.pop_back();
//大小
v.size();

//遍历访问
for(int i = 0; i < v.size(); i ++){
    int item = v[i];//使用下标即可,可以使用迭代器
}

//定义邻接表
vector<int> adjList[N];

map/unordered_map

  • 都提供hash功能,map内部自带排序,unorderd_map没有排序,在只是使用hash的功能上面,使用unordered_map性能会更好,可以进行优化减少TLE

操作:

//定义
map<string, int> mp;
map<pair<int, int>, bool> map
//清空
mp.clear();
//判断是否存在
mp.count(key);
mp.find(key);

//遍历访问
map<string, int>::iterator it;
for(it = mp.start(); it != mp.end(); it ++){
	it->first;
	it->second;
}
//访问,还可以直接下标访问
mp["what"] = 1;

set

  • 不允许重复元素

操作:

//定义
set<int> s;
//清空
s.clear();
//插入
s.insert();
//删除
s.erase();
//查找
s.find(v);//返回迭代器
s.count(v);//存在次数,0或1
//大小
s.size();
//是否为空
s.empty();

//遍历访问
set<int>::iterator it;
for(it = s.begin(); it != s.end(); it ++){
    cout<<*it<<endl;//迭代器类似于指针(*s.begin()).attr
}

string

//长度
s.length();
s.size();
//切割
s.substr(pos, length);//返回从pos下标开始的长度大于length的子串
//切换
char *c = s.c_str();
s = string(c);
//输出
cin>>s;
cout<<s;
printf("%s", s.c_str());//转换为char*输出
//自动重载了比较符号
s1>s2//与strcmp(c1, c2)类似

stack/queue/priority_queue

操作:

//添加
comp.push(a);
//删除
comp.pop();
//访问
stack.top();
queue.front();
queue.back();
priority_queue.top();
//大小
comp.size();
//是否为空
comp.empty();

pair

  • 可以轻松的定义2维相关操作

操作:

//定义
p = make_pair<int, int>;
//访问
p.first;
p.second;
//和其他操作一起使用
vector<pair<int, int> > v;
v.push_back({1, 2});//直接使用大括号定义

重载运算符

//结构体重载运算符
struct Node{
    int a;
    int b;
    bool operator < (const Node &n) const{
        if(a == n.a)
        	return b < p.b;
        return a < p.a;
    }
}
Node nodes[3];
sort(nodes, nodes + 3);//使用重载运算符排序

//定义cmp函数
bool cmp(Node node1, Node node2){
    if(node1.a == node2.a)
    	return node1.b < node2.b;
    return node1.a < node2.a;
}
sort(nodes, nodes + 3, cmp);

//结构体初始化特殊方法
Node node;
node.a = 1;
node.b = 2;
//等价于
Node node = {1, 2};//按顺序进行赋值
//也可以按属性名称赋值
Node node = {.a = 1, .b = 2};
posted @ 2020-02-28 16:21  fabe2ry  阅读(120)  评论(0编辑  收藏  举报