繁体   English   中英

比较C ++中相同向量的元素

[英]Comparing elements of the same vector in c++

下面的函数按以下顺序显示Car向量中的所有元素:

汽车:#1


品牌:宝马

型号:X6

价钱(£):50000

汽车:#2


品牌:本田

模特:爵士

价钱(£):13000

汽车:#3


品牌:马自达

型号:3

价格(英镑):20000

等等

我想根据价格比较向量中的所有汽车,以便找出所有汽车中哪辆汽车更便宜。 是否存在可比较的方法来比较同一向量中的某些字段?

这是一个示例代码:

   void displayCars(vector<Car> carVec)
   {
       if (!carVec.empty())
    {
    cout << "Current Inventory:\n";

    for (unsigned int count = 0; count < carVec.size(); count++)  
    {                                                             
        cout << "\t\t\tCar: #" << (count + 1) << endl          
             << "\t\t___________________________\n\n"
             << "Make: " << carVec[count].getMake() << endl
             << "Model: " << carVec[count].getModel() << endl
             << "Price (£): " << carVec[count].getPrice() << endl
             << endl << endl;
    }




}

}

使用std :: min_element:

auto min = std::min_element( begin(carVec), end(carVec), 
    [](const auto& lh, const auto& rh) {
        return lh.getPrice() < rh.getPrice();
});

std::cout << "Cheapest is: " << min->getModel() << "\n";

如果您将始终按价格排序,则可以执行以下操作:

class Car {
public:
  int price;
  std::string make;
  std::string model;
  int index;
  bool operator<(Car const& otherCar) const;
}

bool Car::operator<(Car const& otherCar) const
{
  return price < otherCar.price;
}

如果您采用这种方式,那么向量上的所有标准排序算法都将使用价格自动进行排序。 否则,您可以为要排序的每件事定义单独的函数:

bool IsCheaper(Car const& Car1, Car const& Car2)
{
   return Car1.price < Car2.price
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM