力扣刷题(c++日常总结)

文章详细介绍了C++中map的不同遍历方式,包括使用范围for循环和迭代器。同时,展示了如何为set自定义pair的哈希函数以及创建无序集合。此外,还讨论了优先队列的使用,包括大根堆和小根堆的设置,并给出示例代码。另外,文章提到了vector的自定义排序、string与数字之间的转换以及多维数组vector的定义和操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

map 的几种遍历方式

for(auto [k,v]:map) {
        cout<<k<<v<<endl;
}
for(auto kv:map) {
        cout<<kv.first<<kv.second<<endl;
}
for(auto it=map.begin();it!=map.end();it++) {
        cout<<it->first<<it->second<<endl;
}

对于set存储pair<int, int>

struct pair_hash {
	template<class T1, class T2>;
	size_t operator () (pair<T1, T2> const &pair) const {
		size_t h1 = hash<T1>()(pair.first);
		size_t h2 = hash<T2>()(pair.second);
		return h1 ^ h2;
}

unprdered_set<pair<int, int>, pair_hash> st;

优先队列

struct data {
	data(int x) {
		a = x;
	}
	int a;
	int b;
	bool operator<(const data& temp) const  {
		return a < temp.a;
	}
};
int main() {
    priority_queue<data> ax;
    data a =  data(1);
    ax.push(data(1));
    ax.push(data(3));
    ax.push(data(2));
    
    cout << ax.top().a << endl;
    ax.pop();
    cout << ax.top().a << endl;
    return 0;
}

在C++中优先队列默认的是大根堆,如果用小根堆则加入greater.
priority_queue<int, vector, less>s;//less表示按照递减(从大到小)的顺序插入元素
priority_queue<int, vector, greater>s;//greater表示按照递增(从小到大)的顺序插入元素
插入是emplace

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


class LESS
{
public:
    bool operator()(const pair<int, int> a, const pair<int, int> b) const {
        return a.second < b.second;
    } 
};


int main()
{
    priority_queue<pair<int, int>, vector<pair<int, int>>, LESS> q;
    q.push({1, 5});
    q.push({4, 78});
    q.push({5, 22});
    q.pop();
    cout << q.top().second << endl;
    cout << q.size() << endl;
    return 0;
}

function
function<double(int, int)> diff = [](int x, int y)->double

tuple

提取的时候搞不清楚就用auto

vector自定义排序

static bool cmp(pair<string, string> a, pair<string, string> b) {
        if (a.first > b.first) return false;
        else if (a.first < b.first) return true;
        else return a.second < b.second;
    }

记得添加static a是后面的那个元素,如果返回true代表交换

string转数字

atoi(s.c_str());

数字转string

to_strinto_string(num);

string

s.substr(0, 2)  #0代表开始位置,2代表取两个字符
s.erase(0, 2)#从零开始的两个字符

queue

q.pop();
q.emplace();
q.front();

定义多维数组vector

vector<vector<vector<int>>> g(x, vector<vector<int>>(y, vector<int>(z));
vector<vetor<int>> g(x, vector<int>(y));

vector添加元素

s.insert(s.begin(), INT_MAX);

tuple

tuple<int, int, int> a;
get<0>(a);
get<1>(a);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值