C++map(unordered_map) 的小于号

博主打题时想从map中取出值最大的元素,起初调试不出样例。经分析,map中每个元素是pair,max_element调用的是pair的小于号,先比较first再比较second。要取出值最大元素,需给max_element传入一个定义operator<的cmp函数。

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

之前打题的时候想从一个map中取出值最大的元素
然后顺手就写了

    auto mx = max_element(mp.begin(), mp.end());

然后怎么调都调不出来样例=_=

后来冷静分析了一下
map&lt;T1,T2&gt;map&lt;T1, T2&gt;map<T1,T2>中的每个元素都是pair&lt;T1,T2&gt;pair&lt;T1, T2&gt;pair<T1,T2>
所以max_elementmax\_elementmax_element调用的应该是pair&lt;T1,T2&gt;pair&lt;T1, T2&gt;pair<T1,T2>的小于号
即先比较firstfirstfirst, 再比较secondsecondsecond
看了下源码果然如此
(在stl_pair.h中)

template<class _T1, class _T2>
    inline _GLIBCXX_CONSTEXPR bool
    operator<(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y)
    { 
    	return __x.first < __y.first
	     || (!(__y.first < __x.first) && __x.second < __y.second); 
	}

所以想取出值最大的元素,需要给max_elementmax\_elementmax_element传入一个cmp函数cmp函数cmp

    auto mx = max_element(mp.begin(), mp.end(), [](const pair<int, int> &x, const pair<int, int> &y){
        return x.second < y.second;
    });

传入的cmpcmpcmp定义的是operator&lt;operator&lt;operator<,注意别写反

以下是C++的A*算法伪代码: ```c++ // 定义节点结构体 struct Node { int x, y; // 节点坐标 int g, h; // g为起点到该点的实际代价,h为该点到终点的估计代价 int f; // f = g + h bool operator<(const Node& other) const { return f > other.f; // 重载小于号,用于优先队列排序 } }; // A*算法 int A_star(Node start, Node end) { priority_queue<Node> pq; // 优先队列,用于存储待扩展的节点 unordered_map<int, unordered_map<int, bool>> visited; // 哈希表,用于记录节点是否已经被访问过 pq.push(start); // 将起点加入优先队列 visited[start.x][start.y] = true; // 标记起点已经被访问过 while (!pq.empty()) { Node cur = pq.top(); // 取出f值最小的节点 pq.pop(); if (cur.x == end.x && cur.y == end.y) { // 如果当前节点是终点,返回起点到终点的代价 return cur.g; } for (int i = 0; i < 4; i++) { // 遍历当前节点的四个相邻节点 int nx = cur.x + dx[i], ny = cur.y + dy[i]; // 计算相邻节点的坐标 if (nx < 0 || nx >= n || ny < 0 || ny >= m) { // 如果相邻节点越界,跳过 continue; } if (visited[nx][ny]) { // 如果相邻节点已经被访问过,跳过 continue; } int ng = cur.g + 1; // 计算起点到相邻节点的实际代价 int nh = heuristic(nx, ny, end.x, end.y); // 计算相邻节点到终点的估计代价 int nf = ng + nh; // 计算相邻节点的f值 pq.push({nx, ny, ng, nh, nf}); // 将相邻节点加入优先队列 visited[nx][ny] = true; // 标记相邻节点已经被访问过 } } return -1; // 如果无法到达终点,返回-1 } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值