读取结构数组的二进制表达式的无效操作数
invalid operand to binary expression reading an array of struct
我正在尝试解决著名的分数背包问题。我需要一个结构来连接值和权重。现在我想读取结构项的数组,但它给了我这个:
invalid expression error
#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
我正在尝试解决著名的分数背包问题。我需要一个结构来连接值和权重。现在我想读取结构项的数组,但它给了我这个:
invalid expression error
#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