首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >一种高效的三向量排序算法

一种高效的三向量排序算法
EN

Stack Overflow用户
提问于 2015-04-21 00:25:53
回答 3查看 168关注 0票数 1

我有3个向量,categorydescriptionprice我写了这段代码,将category组织的向量放到一个名为menuFile的文件中

代码语言:javascript
运行
复制
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;
    }
}      

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

EN

Stack Overflow用户

发布于 2015-04-21 00:36:54

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

例如:

代码语言:javascript
运行
复制
struct Menu {
    string category;
    string description;
    int price;
};

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

代码语言:javascript
运行
复制
struct Menu {
    string category;
    string description;
    int price;
    bool operator < (const Menu& rhs) const {
        return (this->price < rhs.price);
    }
};

然后,只需为该结构创建一个向量并对其进行排序。

代码语言:javascript
运行
复制
vector<Menu> menu;
// do something, insert data
sort(menu.begin(),menu.end());

然后相应地输出。

代码语言:javascript
运行
复制
for(int x = 0; x < menu.size(); x++){
    menuFile << menu[x].category << ":" << menu[x].description << ":" << menu[x].price << endl;
}  
票数 4
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29753289

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档