代码的主要功能中“Item arr[30]”行中的错误是什么?
它显示错误“没有匹配的函数来调用 Item::Item()”。请任何人修复代码中的错误。
这道题属于背包问题。我们有 N 件物品,其中每件物品都有一些重量和与之相关的价值。我们还得到了一个容量为 W 的袋子,[即袋子最多可以容纳 W 重量]。目标是将物品放入包中,使与它们相关的价值总和尽可能大。
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
class Item {
int value;
int weight;
public:
Item(int value, int weight)
: value(value), weight(weight)
{
}
int get_value() {
return value;
}
int get_weight() {
return weight;
}
};
bool cmp(Item a, Item b)
{
double r1 = (double)a.get_value() / (double)a.get_weight();
double r2 = (double)b.get_value() / (double)b.get_weight();
return r1 > r2;
}
double MaxValue(Item arr[], int N, int W)
{
sort(arr, arr + N, cmp);
int curWeight = 0;
double finalvalue = 0.0;
for (int i = 0; i < N; i++) {
if (curWeight + arr[i].get_weight() <= W) {
curWeight += arr[i].get_weight();
finalvalue += arr[i].get_value();
}
else {
int remain = W - curWeight;
finalvalue += arr[i].get_value() * ((double)remain / (double)arr[i].get_weight());
break;
}
}
return finalvalue;
}
int main() {
int N;
int W;
cin >> N >> W;
Item arr[30];
for(int i = 0; i < N; i++) {
int value, weight;
cin >> value >> weight;
arr[i] = Item(value, weight);
}
cout << MaxValue(arr, N, W);
}
您需要为
Item
添加一个默认构造函数。将为数组中的每个项目调用默认构造函数。像这样的
class Item {
int value;
int weight;
public:
Item() : value(-1), weight(-1) // dummy values
{
}
Item(int value, int weight)
: value(value), weight(weight)
{
}
...
C++ 中的每个对象都必须构造。对于数组,这意味着必须有一个默认构造函数,可以在构造数组本身时调用它。
如评论中所述,您还可以添加
Item() = default;
为默认构造函数提供默认含义(双重默认)。在这种情况下,默认的默认构造函数将保留
value
和 weight
未初始化。这也许是你一直想要的。
C++ 的规则之一是,没有任何构造函数的类会自动获得默认的默认构造函数。但是一旦您添加自己的构造函数,默认的默认构造函数就会消失。这就是你的代码中发生的事情。