使用c ++中对象中函数的结果对对象数组进行排序

时间:2017-01-25 19:21:49

标签: c++ arrays sorting

我有一个程序可以创建一个指向对象的指针数组。指针所指向的类存储商品的净价,并具有计算对象总价的功能。

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中有一种排序算法,但我认为它不会对我有用,或者至少我不知道如何让它工作。

网站上存在使用排序的类似问题的解决方案,但是我找不到任何解决方案显示它在此上下文中使用。

2 个答案:

答案 0 :(得分:4)

std::sort(p, p+n,
          [](Product* p1, Product* p2)
          {
              return p1->getGrossPrice() < p2->getGrossPrise();
          }); 

这是对标准排序函数std::sort的调用。我们将开始和结束迭代器(在本例中为指针)传递给我们要进行排序的范围,第三个参数是一个返回true的函数对象,它的第一个参数严格少于(strict weak ordering我们希望按照比第二个参数排序,否则为false。以[]开头的部分称为lambda-expression:在其他语言中,类似对象可称为匿名函数。它是在C ++ 11中引入的。

答案 1 :(得分:0)

使用range-v3,您可以简单地执行(使用投影):

ranges::sort(prods, std::less<>{}, &Product::getGrossPrice);

Demo