c++的常见问题

0.

c++string中find()返回值是字母在母串中的位置(下标记录),如果没有找到,那么会返回一个特别的标记npos(可以看成是一个int型的数),而不是返回0或者null。比如:

#include <bits/stdc++.h>
using namespace std;
int main(){
	string str = "huohaiyuan";
	if(str.find('z') == str.npos) 
		cout << "no find";
	else	
		cout << "find";	
} 

使用find方法查找一个字符串中有几个某字串。

	int ans = 0, f = 0;
	while(str.find("hhhh",f) != str.npos){
		ans++; f = str.find("FeiMa",f)+1;
	}

1.优先队列 priority_queue

方法:

和队列操作基本相同:
top 访问队头元素 // 不同点
pop 弹出队头元素
empty 队列是否为空
size 返回队列内元素个数
push 插入元素到队尾 (并排序)
emplace 原地构造一个元素并插入队列

默认类型:

priority_queue<int> que;  // 默认大顶推, 即从大到小 
priority_queue<int, vector<int>, greater<int> > que1; // 小顶堆 
priority_queue<int, vector<int>, less<int> > que2;  // 大顶堆 

自定义类型:

//方法1 运算符重载 <
struct node{
    int x, y;
    bool operator < (const node& a) const{
        return x < a.x; //大顶堆
    }
};
priority_queue<node> que3;

两个变量时可以直接使用pair<>;
pair排序时是先根据first,再根据second。

typedef pair<int, int> PII;
priority_queue<PII, vector<PII>, greater<PII> > heap; // 定义一个小根堆

2.格式

cout输出对a保留f位小数

cout<< fixed << setprecision(f) << a;

3.运算符重载

struct node{
	string id, name;
	int a, b, c, d, i;
};
node arr[105];

bool cmp(node a, node b){
	if(a.d == b.d) return a.i < b.i;
	return a.d > b.d;
}

bool operator < (const node& a, const node& b){
	if(a.d == b.d) return a.i < b.i;
	return a.d > b.d;
}

4 判断map中元素是否存在

1.可以使用map中的find()方法,如果存在返回的是该地址的指针,不存在返回map 最后的指针即map.end()。
2.使用count()方法,如果为0则不存在。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值