读取struct数组的二进制表达式的无效操作数

问题描述 投票:-2回答:1

我正在尝试实现分数背包的着名问题。我需要一个结构来连接值和权重。现在我想读取struct item的数组,但它给了我这个:

表达式无效错误

#include <iostream>
#include <vector>
#include <string>

using std::vector;
using namespace std;

// Structure for an item which stores weight and corresponding
// value of Item
struct Item
{
    int value, weight;
    // Constructor
    Item(int value, int weight) : value(value), weight(weight) {}
};

int main()
{    
    int n;
    int W;
    std::cin >> n >> W;

    vector<Item> arr(n);
    for (int i = 0; i < n; i++) {
        std::cin >> arr[i];
    }

    cout << "Maximum value we can obtain = " << fractionalKnapsack(W, arr, n);
    return 0;
}
c++ struct knapsack-problem
1个回答
1
投票

arrvector类型的Item。要访问Item字段,如果您使用的是.,则必须使用->pointer。使用cin >> arr[i]你试图将char输入Item的一个对象。

试试这个:std::cin >> arr[i].value

© www.soinside.com 2019 - 2024. All rights reserved.