vector<pair<int,int>> 的使用和sort排序

关于vector<pair<int,int>> 的使用,以及sort函数的使用,sort默认是按照pair的first升序排序,如果first相同,则按照second进行升序排序,具体代码如下:

#include <iostream>
#include <vector>
#include<algorithm>
using namespace std;

//根据first的值升序排序,如果first值相等,则根据second排序
bool cmp1(pair<int, int>a, pair<int, int>b)
{
    if (a.first != b.first)
        return a.first < b.first;
    else if (a.first == b.first && a.second != b.second)
        return a.second < b.second;
    else
        return b.first < a.first;
}

//根据second的值升序排序
bool cmp2(pair<int, int>a, pair<int, int>b)
{
    return a.second < b.second;
}

int main()
{
    vector<pair<int, int>>vec;
    vec.push_back({ 1,2 });
    vec.push_back({ 1,1 });
    vec.push_back({ 3,3 });
    vec.push_back({ 2,1 });
    vec.push_back({ 3,4 });
    sort(vec.begin(), vec.end(), cmp1);
    cout << "根据first的值升序排序:" << endl;
    for (auto it = vec.begin(); it != vec.end(); it++)
    {
        cout << "(" << it->first << "," << it->second << ")" << endl;
    }
    sort(vec.begin(), vec.end(), cmp2);
    cout << "根据second的值升序排序:" << endl;
    for (auto it = vec.begin(); it != vec.end(); it++)
    {
        cout << "(" << it->first << "," << it->second << ")" << endl;
    }
}

运行结果如下:
在这里插入图片描述
附上一道MeiTuan的笔试题,其中便使用了vector<pair<int,int>> 和sort排序。
题目如下:
在这里插入图片描述
在这里插入图片描述
实现的代码如下:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

//根据first的值升序排序,如果first值相等,则根据second排序
bool cmp1(pair<int, int>a, pair<int, int>b)
{
	if (a.first != b.first)
		return a.first < b.first;
	else if (a.first == b.first && a.second != b.second)
		return a.second < b.second;
	else
		return b.first < a.first;
}

int HaMadun(int x, int y, int a, int b) {
	return abs(x - a) + abs(y - b);
}

int main() {
	int n; //棋盘的大小
	cin >> n;
	int x1, y1; //第一个定位器坐标
	cin >> x1 >> y1;
	int x2, y2;
	cin >> x2 >> y2;
	int x3, y3;
	cin >> x3 >> y3;
	int a, b, c; //分别表示第一、二、三个定位器到信标的曼哈顿距离
	cin >> a >> b >> c;

	vector<pair<int,int>> ans; //存储符合条件的坐标
	//将同时满足a、b、c距离条件的坐标进行存储
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			if (a == HaMadun(x1, y1, i, j) 
				&& b == HaMadun(x2, y2, i, j)
				&& c == HaMadun(x3, y3, i, j)) {
				ans.push_back({i,j});
			}
		}
	}
	//排序
	sort(ans.begin(), ans.end(), cmp1);
	cout << ans[0].first << " " << ans[0].second << endl;

	return 0;
}

运行结果如下:
在这里插入图片描述

  • 7
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值