我正在尝试实现分数背包的着名问题。我需要一个结构来连接值和权重。现在我想读取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;
}
arr
是vector
类型的Item
。要访问Item
字段,如果您使用的是.
,则必须使用->
或pointer
。使用cin >> arr[i]
你试图将char
输入Item
的一个对象。
试试这个:std::cin >> arr[i].value