繁体   English   中英

试图在 C++ 中创建一个包含结构的数组?

[英]Trying to Create an array holding a Struct in C++?

我正在尝试使用 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.

您最大的编译问题是:

您必须为您的Item提供一个默认构造函数,否则,它不能存在于未初始化的数组中。

struct Item
{
    int value, weight;
    // Constructor
    Item(int value, int weight)
    {
        this->value = value;
        this->weight = weight;
    }

    Item() : value(0), weight(0)
    {};
};

当你像这样调用 knap 时,你的参数似乎被颠倒了。 此外,您传递不带括号的数组:

    cout << knap(w, arr[], n);

你可能的意思是:

    cout << knap(n, arr, w);

正如其他人指出的那样:

    struct Item arr[n];

这不是有效的 C++,但 g++ 允许。

更好的:

    std::vector<Item> arr;    // #include <vector>
    arr.resize(n);

然后你把它作为一个指针传递给你的 knap function (它是这样写的:

cout << knap(n, arr.data(), w);

或者,修改您的 knap function 以采用向量:

double knap(vector<Item>& arr, double w)
{
    int n = arr.size();

所以你可以说:

cout << knap(arr, w);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM