我有3个向量,category,description和price我写了这段代码,将category组织的向量放到一个名为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;
}
} 但这似乎不是一个非常有效的方法。这是一种更好的方法吗?
发布于 2015-04-21 00:36:54
我认为您应该创建一个结构来处理这三种类型的数据,然后为它创建一个向量。
例如:
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<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;
} https://stackoverflow.com/questions/29753289
复制相似问题