【发布时间】:2021-08-05 03:17:07
【问题描述】:
我正在尝试使用 c++ 中的结构创建一个数组,该结构需要两个变量,即值和权重。所以我创建了一个数组,它在这样的一个元素中具有值和权重 Arr[]={{1,2},{3,4}}...如果我打电话,我想要那个 Arr[0].value 和 Arr[0].weight 那么它应该分别返回 1 和 2 但我认为我做错了,因为我遇到了很多错误
//Heres my Item struct....
struct Item
{
int value, weight;
// Constructor
Item(int value, int weight)
{
this->value = value;
this->weight = weight;
}
};
//This is my knapsack function
double knap(int n, Item arr[], double w)
{
double v = 0;
double am = 0;
for (int i = 0; i < n; ++i)
{
if (w == 0)
{
return v;
}
am = min(arr[i].weight, w);
v += am * (arr[i].value / arr[i].weight);
w -= am;
}
return v;
}
//Heres my main() function
int main()
{
int n;
double w;
cin >> n >> w;
struct Item arr[n];
for (int i = 0; i < n; ++i)
{
cin >> arr[i].value >> arr[i].weight;
}
//this is a fuction i want to run
cout << knap(w, arr[], n);
}
这里是错误
/storage/emulated/0/coursera/max money2.cpp:50:14:
errorr: no matching constructor for initialization of
'structt Item [n]'
struct Item arr[n];
^
/storage/emulated/0/coursera/max money2.cpp:7:9: note:
candidatee constructor (the implicit copy constructor)
not viable: requires 1 argument, but 0 were provided
struct Item
^
/storage/emulated/0/coursera/max money2.cpp:7:9: note:
candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 0 were provided
/storage/emulated/0/coursera/max money2.cpp:11:3: note: candidate constructor not viable: requires 2 arguments, but 0 were provided
Item(int value, int weight)
^
2 errors generated.
【问题讨论】:
-
struct Item arr[n];-- 这不是有效的 C++。数组的大小必须由常量而不是运行时值表示。其次,这里不需要struct——代码看起来更像C,而不是C++。而是:std::vector<Item> arr(n);. -
您遇到了什么错误?什么是
knap()签名?请编辑您的问题以包含minimal reproducible example -
我已经编辑了我的帖子并添加了错误图像以及 knap() 函数@Slava
-
顺便说一句,
knap()期望int作为第一个参数,double作为最后一个参数,但您使用double和int调用它。并且您的错误不可见,请将它们作为文本发布 -
您希望
struct Item arr[n];行完成什么?构造n类型为Item的对象?没有构造参数如何构造它们? (这就是错误消息的意思。)
标签: c++ arrays function struct constructor