c++ - 读取结构数组的二进制表达式的操作数无效
问题描述
我正在尝试实现分数背包著名的问题。我需要一个结构来连接值和权重。现在我想读取 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]
您正在尝试将 a 输入char
到 的对象Item
。
尝试这个:std::cin >> arr[i].value
推荐阅读
- angular - 与 ngx-pagination 一起使用时,ngFor 索引重置为 0
- wordpress - 如何在 WooCommerce 中的产品结构化数据 (Schema.org) 中添加产品图像和描述
- python - 如何获取 askstring 的文本?
- swift - 如何允许 ForEach 布局项在 SwiftUI 中显示数组中的重复项?
- express - 当我尝试使用快速路由器访问参数值时,我变得不确定
- azure-active-directory - API 身份验证错误 - 为 code 参数提供的值无效。代码已过期
- area - 你如何找到位于三个圆柱体中的固体边界的表面积?
- sql - 子查询获取 2 列
- reactjs - 材质 UI 表不适用于 react-hook-form
- node.js - 如何创建一个 html 表单并将其嵌入到 iframe 中?