【发布时间】:2015-04-20 16:25:52
【问题描述】:
我有 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;
}
}
但这似乎不是一个非常有效的方法。有更好的方法吗?
【问题讨论】:
-
category、description、price分别是什么类型?它们只是字符串吗?似乎您希望struct将此数据作为一个组包含,然后您可以编写自定义比较运算符并在输出之前在您的向量上调用std::sort。 -
您几乎肯定希望从具有三个成员的结构(或类)开始,而不是三个向量,然后创建这些结构的向量。这样可以很容易地按照您选择的顺序对项目进行排序。
-
考虑在 codereview.stackexchange 上发布这个,那里似乎更合适。
-
是 'category' 唯一的排序方案(否则,您可能会看看 boost.org/doc/libs/1_58_0/libs/multi_index/doc/index.html - 虽然有点复杂)