技巧:C/C++常用库函数

一、map相关
1、map定义时添加参数 less<>/greater<>可以设置map内排序为升降序;
2、map.find(val)返回迭代器,失败是迭代器指针指向map.end()
3、map.erase(it), map.erase(it1, it2),map.erase(key)
二、algorithm库
1、max(a, b), min(a, b), abs(val)
2、swap(a, b)
3、reverse(it1, it2)逆转序列
4、sort(it1,it2, cmp),cmp可在参数中定义:[] ( type a, type b ) { return a < b; }
5、stable_sort(it1, it2, cmp)稳定排序
6、fill(it1, it2, val)
7、max_element (it1, it2, cmp);返回指针

三、vector相关
1、vector.push_back()尾部插入
2、vector.pop_back()
3、vector.earase(it) vector.erase(it1, it2)
4、vector.insert(it, elem)
5、vector.back()
6、重新初始化尽量使用fill(),避免使用resize()

四、set(有序自动去重集合)相关
1、仅支持set.insert()
2、set.find(val),失配返回set.end()
3、set.erase(val) set.erase(it), set.erase(it1, it2)
4、存储结构体类型需要对运算符’<'重载。

例:对结构体node{num_a, num_b}'<'重载,实现按node.num_a升序排序;
typedef struct node
{
	int num_a, num_b;
	bool operator < (const node a)const
	{
		return num_a < a.num_a;
	}
};
set<node, less<node>> ss;

五、string相关
1、支持+、+=
2、支持比较运算符(字典序)
3、str.erase(it), str.erase(it1, it2), str.erase(pos, len)
4、str.find(substr)返回首次出现位置,失配返回-1
5、str.substr(pos, len)取子串
6、str.insert(pos, string)
6、str.replace(pos, len, str2);将str下标pos起长度为len的字符串替换为str2
7、scanf()输入

string str;
str.resize(n);//必须预申请空间
scanf("%s", &str[0]);

8、printf()输出

printf("%s", str.c_str());

9、string转int:
(1)atoi()
(2)sscanf(char *, “%d”, &intager);
10、int转string:
(1)to_string()
(2)sprintf(str, “%d”, intager);
11、string() 将C字符串转为string
六、queue相关

1、q.push() q.pop(), q.front(),q.rear()
2、s.push() s.pop() s.top()
3、优先级队列

#include <queue>
#Include <>
priority_queue<type, 底层容器类型, less<type>升序 / greater<type>降序(默认)>

(1)基本数据类型

priority_queue<int> q;
priority_queue<int, vector<int>, greater<int>> q
//等价定义

(2)结构体类型重载运算符

struct node
{
    int key;
    bool operator > (const node a) const//重载>运算符
    {
        return key > a.key;
    }
    bool operator < (const node a) const//重载<运算符
    {
        return key > a.key;
    }
};
priority_queue<node, vector<node>, greater<node>> q; //less<node>降序

七、pair相关
1、pair<type1, type2>
2、make_pair(val1, val2)
3、pair->first, pair->second

八、VS2008不提供支持的函数/语法
1、unordered_map
2、auto禁用,迭代器使用class::iterator it;

九、结构体初始化赋初值

struct node
{
	int a, b;
	node()
	{
		a = 10;
		b = -1;
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值