无效操作数以二进制读取结构的阵列

invalid operand to binary expression reading an array of struct

本文关键字:结构 阵列 读取 二进制 操作数 无效      更新时间:2023-10-16

我正在尝试实现分数符号著名问题。我需要一个结构来连接值和权重。现在我想阅读结构项目的数组,但是它给了我这一点:

无效的表达式错误

#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;
}

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

尝试以下操作:std::cin >> arr[i].value