首页 > 解决方案 > 读取结构数组的二进制表达式的操作数无效

问题描述

我正在尝试实现分数背包著名的问题。我需要一个结构来连接值和权重。现在我想读取 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++structknapsack-problem

解决方案


arr是一个vector类型的对象Item。要访问Item字段,您必须使用.或者->如果您使用的是pointer. 使用cin >> arr[i]您正在尝试将 a 输入char到 的对象Item

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


推荐阅读