第28465题 单选题
使用C++ STL的std::sort对自定义结构体进行多条件排序时,以下哪个自定义比较函数是正确的?

我们定义了如下自定义结构体:

struct Product {
    std::string name;
    double price;
    int stock;
};

现在需要将Product数组按照price从高到低降序排序,若两个元素的price相同,则按照stock从低到高升序排序,以下哪个比较函数可以正确实现该需求?

A

bool compare(const Product& a, const Product& b) { return a.price > b.price || a.stock < b.stock; }

B

bool compare(const Product& a, const Product& b) { if (a.price != b.price) { return a.price > b.price; } return a.stock < b.stock; }

C

bool compare(const Product& a, const Product& b) { return a.price < b.price && a.stock < b.stock; }

D

bool compare(const Product& a, b) { return a.price > b.price && a.stock < b.stock; }

程序运行统计
暂无判题统计
提交0次 正确率0.00%
答案解析