我有products.txt文件:
Chocolate 5 250
Car 5000 1
Chips 3 350
...
您可以看到数据按顺序排列:名称,价格,数量。我需要按价格对产品分类。我已经确定文件中有多少产品,以及所有产品的总价值是多少。
我有一个结构:
struct product {
char name[20];
int price;
int quantity;
};
我尝试使用标准的排序算法,但我不知道如何应用它。
您应该先读取数据,将其写入向量,对其进行排序,然后将所需格式的排序数据写入* .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。