Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用c+中对象中函数的结果对对象数组进行排序+;_C++_Arrays_Sorting - Fatal编程技术网

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

C++ 使用c+中对象中函数的结果对对象数组进行排序+;,c++,arrays,sorting,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 softw

我有一个程序,可以创建指向对象的指针数组。指针指向的类存储项目的净价,并具有计算对象总价的函数

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;
产品*p[10];
第*b册;
软件*s;
双倍价格;
价格;
b=新书(价格);
价格;
s=新软件(价格);
cout
std::sort(p,p+n,
[](产品*p1,产品*p2)
{
返回p1->getGrossPrice()getGrossPrise();
}); 
这是对标准排序函数
std::sort
的调用。我们将开始迭代器和结束迭代器(本例中为指针)传递给要排序的范围,第三个参数是返回true的函数对象,它的第一个参数严格小于第二个参数(根据我们要排序的参数),否则为false。以[]开头的部分称为:在其他语言中,类似的对象可以称为匿名函数。它是在C++11中引入的。

std::sort(p,p+n,
[](产品*p1,产品*p2)
{
返回p1->getGrossPrice()getGrossPrise();
}); 
这是对标准排序函数
std::sort
的调用。我们将开始迭代器和结束迭代器(本例中为指针)传递给要排序的范围,第三个参数是返回true的函数对象,它的第一个参数严格小于第二个参数(根据我们要排序的参数),否则为false。以[]开头的部分称为:在其他语言中,类似的对象可以称为匿名函数。它是在C++11中引入的。

使用,您只需(使用投影)即可:

ranges::sort(prods、std::less{},&Product::getGrossPrice);
使用,您只需(使用投影)即可:

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

getGrossPrice()是虚拟的吗?然后,您可以使用一个自定义的functor调用sort,该functor调用可能重复的is
getGrossPrice()
virtual?然后你可以用一个自定义的functor调用sort,这个functor调用Amen的可能的副本,请不要只是发布代码。这对提问者理解答案没有帮助。如果可以,请编辑答案并添加简短的解释。可能需要添加C++11>并为pre添加一个解决方案。各位,请耐心一点。@ArmenTsirunyan关于您的耐心请求:可以合理地假设,一旦有人发布了答案,这就是他们打算发布的完整答案。人们立即批评答案是正确的。@FrançoisAndrieux另一方面,SO系统鼓励首先发布,所以Armens程序是常见的。乔恩·斯基特也鼓励这样做。阿门,请不要只是张贴代码。这对提问者理解答案没有帮助。如果可以,请编辑答案并添加简短的解释。可能需要添加C++11>并为pre添加一个解决方案。各位,请耐心一点。@ArmenTsirunyan关于您的耐心请求:可以合理地假设,一旦有人发布了答案,这就是他们打算发布的完整答案。人们立即批评答案是正确的。@FrançoisAndrieux另一方面,SO系统鼓励首先发布,所以Armens程序是常见的。乔恩·斯基特也鼓励这种做法。
std::sort(p, p+n,
          [](Product* p1, Product* p2)
          {
              return p1->getGrossPrice() < p2->getGrossPrise();
          }); 
ranges::sort(prods, std::less<>{}, &Product::getGrossPrice);