gpt4 book ai didi

c++ - 3个 vector 的高效排序算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:18:14 33 4
gpt4 key购买 nike

我有 3 个 vector ,category descriptionprice 我写了这段代码来放置按 category 组织的 vector 到名为 menuFile 的文件中:

for(int x = 0; x < _category.size(); x++){
if(_category[x].compare("Starter") == 0){
menuFile << _category[x] << ":" << _description[x] << ":" << _price[x] << endl;
}
}

for(int x = 0; x < _category.size(); x++){
if(_category[x].compare("Main") == 0){
menuFile << _category[x] << ":" << _description[x] << ":" << _price[x] << endl;
}
}

for(int x = 0; x < _category.size(); x++){
if(_category[x].compare("Pudding") == 0){
menuFile << _category[x] << ":" << _description[x] << ":" << _price[x] << endl;
}
}

for(int x = 0; x < _category.size(); x++){
if(_category[x].compare("Drink") == 0){
menuFile << _category[x] << ":" << _description[x] << ":" << _price[x] << endl;
}
}

但这似乎不是一个非常有效的方法。这是更好的方法吗?

最佳答案

我认为您应该创建一个结构来处理这三种类型的数据,然后为它创建一个 vector 。

例如:

struct Menu {
string category;
string description;
int price;
};

然后我会建议您实现一个比较器来决定如何对数据进行排序。假设按价格排序(当然,您可以决定如何实现重载运算符)。

struct Menu {
string category;
string description;
int price;
bool operator < (const Menu& rhs) const {
return (this->price < rhs.price);
}
};

然后为这个结构创建一个 vector 并对其进行排序。

vector<Menu> menu;
// do something, insert data
sort(menu.begin(),menu.end());

然后相应地输出。

for(int x = 0; x < menu.size(); x++){
menuFile << menu[x].category << ":" << menu[x].description << ":" << menu[x].price << endl;
}

关于c++ - 3个 vector 的高效排序算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29753289/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com