簡體   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