题解 | #找最小数#

找最小数

https://www.nowcoder.com/practice/ba91786c4759403992896d859e87a6cd

#include<iostream>
#include<vector>
#include<algorithm>

struct Two//定义结构体
{
    int x, y;
    Two(int a, int b)//构造函数,用来对结构体变量赋值
        : x(a), y(b)
    {
    }
};

bool compare(const Two& A, const Two& B)//自己编写比较函数,作为sort函数的参数
{
    if(A.x < B.x)//先按x的值从小到大排列
    {
        return true;
    }else if(A.x > B.x)
    {
        return false;
    }
    return A.y < B.y;//如果x的值相等,按y的值从小到大排列
}

int main()
{
    int n;
    while (std::cin >> n)
    {
        int a, b;
        std::vector<Two> v;
        v.reserve(n);//预先指定vector需要的内存数量,可加快执行速度
        for(int i = 0;i < n;i++)
        {
            std::cin >> a >> b;
            v.emplace_back(a, b);//不直接传递对象,而将参数传入
        }
        std::sort(v.begin(), v.end(), compare);
        std::cout << v[0].x << " " << v[0].y << std::endl;
    } 
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务