按价格对文件中的产品进行排序

时间:2020-05-15 12:03:22

标签: c++ file structure

我有products.txt文件:

Chocolate 5 250
Car 5000 1 
Chips 3 350
...

您会看到数据按顺序排列:名称,价格,数量。我需要按价格对产品分类。我已经确定文件中有多少产品,以及所有产品的总价值是多少。

我有一个结构:

struct product {
  char name[20];
  int price;
  int quantity;    
  };

我尝试使用标准的排序算法,但是我不知道如何应用它。

1 个答案:

答案 0 :(得分:0)

您应该首先读取数据,将其写入向量,对其进行排序,然后将所需格式的排序数据写入* .txt文件。使用std::sort函数可以定义如何比较两个对象。您可以执行以下操作:

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>

struct product {
  std::string name;
  int price;
  int quantity;    
  };

int main()
{
    std::vector<product> products = {{"first",10000,1},{"second",100,1},{"third",10,1}};
    std::sort(products.begin(),products.end(),[](const product &a, const product &b){
        return a.price < b.price;
    });

    for (const auto &el : products)
        std::cout << el.name << "  " << el.price << std::endl;
}  

这将打印:

third  10
second  100
first  10000

这里是live demo