2017-01-25 68 views
0

我有一个程序可以创建一个指向对象的指针数组。指针指向的类存储一个项目的净价格,并具有计算对象总价格的功能。使用C++中的对象函数的结果对对象数组排序

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

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

+0

是'getGrossPrice()'虚拟?那么你可以调用一个自定义函数来调用排序 –

+1

[矢量排序与对象?](http://stackoverflow.com/questions/14081335/algorithm-vector-sort-with-objects) –

回答

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

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

+0

阿门,请不要只发布代码。这对提问者理解答案没有帮助。如果可以,请编辑答案并添加简要说明。 – mascoj

+0

可能要添加C++ 11>并可能为pre添加解决方案。 –

+0

有点耐心,伙计们。 –

0

随着range-v3,你可以简单地做(用投影):

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

Demo