我有一个程序可以创建指向对象的指针数组。指针指向的类存储了一个项目的净价,并具有计算该对象总价的函数。
Product *p[10];
Book *b;
Software *s;
double price;
cout << "Enter the price of the book: " << endl;
cin >> price;
b = new Book(price);
cout << "Enter the price of the software: " << endl;
cin >> price;
s = new Software(price);
cout << "Gross price of book: " << b->getGrossPrice() << endl;
cout << "Gross price of software: " << s->getGrossPrice() << endl;
p[0] = b;
p[1] = s;
有没有办法按照毛价的升序对数组进行排序?
我知道 STL 中有一种排序算法,但我认为它对我不起作用,或者至少我不确定如何让它起作用。
网站上有使用排序的类似问题的解决方案,但我找不到任何解决方案表明它在这种情况下使用。
最佳答案
std::sort(p, p+n,
[](Product* p1, Product* p2)
{
return p1->getGrossPrice() < p2->getGrossPrise();
});
这是对标准排序函数 std::sort
的调用。我们将开始和结束迭代器(在本例中为指针)传递给我们要排序的范围,第三个参数是一个返回 true 的函数对象,它的第一个参数严格小于(根据我们想要的 strict weak ordering排序根据)而不是第二个参数,否则为假。以 [] 开头的部分称为 lambda-expression :在其他语言中,类似的对象可以称为匿名函数。它是在 C++11 中引入的。
关于c++ - 使用c++中对象中函数的结果对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41859926/