编辑代码

#include <iostream>
#include <algorithm>
#include <list>
#include <vector>

using namespace std;

struct Item {
        string name;
        float totalWeight;
        float totalValue;

        Item(string itemName, float weight, float value) {
            name = itemName;
            totalWeight = weight;
            totalValue = value;
        }
};

struct PackedItem {
    string name;
    float packedWeight;

    PackedItem(string itemName, float weight) {
        name = itemName;
        packedWeight = weight;
    }
};

void printItems(std::list<PackedItem> *packedItems) {
    for (std::list<PackedItem>::iterator i = packedItems->begin(); i != packedItems->end(); ++i)
    {
        cout << i->name << ":" << i->packedWeight << endl;
    }
    
}

bool compareGreaterItemUnitPrice(Item left, Item right) {
    return (left.totalValue/left.totalWeight) > (right.totalValue/right.totalWeight);
}


void packItem(float packageWeight, std::vector<Item> *items, std::list<PackedItem> *packedItems) {
    //按照从大到小顺序对items进行排序
    sort(items->begin(), items->end(), compareGreaterItemUnitPrice);

    float curWeight = 0.0;
    //将豆子装入背包
    for(std::vector<Item>::iterator i = items->begin(); i != items->end(); ++i) {
        if (curWeight + i->totalWeight < packageWeight) {
            packedItems->push_back(PackedItem(i->name, i->totalWeight));
            curWeight += i->totalWeight;
        }
        else {
            packedItems->push_back(PackedItem(i->name, packageWeight - curWeight));
            break;
        }

    }
}

int main(){
    std:vector<Item> items;

    //初始化装包豆子
    items.push_back(Item("soybean", 100, 100));
    items.push_back(Item("mung bean", 30, 90));
    items.push_back(Item("red bean", 60, 120));
    items.push_back(Item("black bean", 20, 80));
    items.push_back(Item("green bean", 50, 75));
   
    std::list<PackedItem> packedItems;

    packItem(100, &items, &packedItems);

    printItems(&packedItems);


}