簡體   English   中英

我正在嘗試向我的堆棧中輸入一個值,但它給了我一個錯誤

[英]I am trying to input a value into my stack but it gives me an error

因為當我將數字 2 輸入我的變量時,它告訴我它沒有定義? 有幫助嗎?

int plusThree(){

input 2 -> stack;

return stack;

}

繼續我的評論,跳出的第一個問題是您將int large1, int large2聲明為twoLargest()的參數。 當您在參數列表中放置變量(不是引用也不是指針)時,function 會收到駐留在函數堆棧上的變量的本地副本,並且當 function 返回並返回時,您對本地副本所做的任何更改都將丟失堆棧被銷毀(例如函數堆棧 memory 被釋放以供重新使用)

在 C++ 中,您可以將引用作為參數傳遞,從而允許 function 對來自調用 function 的實際變量進行操作,而不是對副本進行操作。 因此,您想要引用large1large2 ,而不是int large1, int large2 ,例如int& large1, int& large2

跳出的下一個錯誤是您嘗試將arraymain()作為int arr[]傳遞給您的 function。 main()中聲明std::vector<int> array; ,所以array的類型是std::vector<int> ,而不是int[] (這需要一個大小不是不完整的類型)您還想將array作為參考傳遞,以避免為 function 制作array的完整副本 - 並且 - 因為array在您的 function 中沒有更改,您應該將引用聲明為const告訴編譯器它不會在 function 中更改,這允許編譯器進一步優化其使用。

總而言之,將 function 類型更改為void因為它不返回任何值並修復語法和符號問題並正確初始化為類型范圍中的最低值,因為您正在尋找max ,您將擁有:

/* type of function is 'void' it does not return a value.
 * by passing references to large1 and large2 the function
 * will operate on the variable passed from main() instead
 * of local "copies" of the variables.
 */ 
void twoLargest(const std::vector<int>& arr, int& large1, int& large2)
{
    /* always initialize max variables to min of range to start */
    large1 = std::numeric_limits<int>::min();
    large2 = std::numeric_limits<int>::min();
    
    for (size_t i = 0; i < arr.size(); i++) {
        if (arr[i] > large1) {
            large2 = large1;
            large1 = arr[i];
        }
        else if (arr[i] > large2) {
            large2 = arr[i];
        }
    }
}

注意:如果值都是負數,將large1large2初始化為0將不起作用。您還需要為類型的max()min() #include <limits> 。)

為了傳遞large1large2作為對twoLargest()的引用,您傳遞的int變量必須在調用 function(此處為main() )中聲明。 因此,您需要在要傳遞的main()中聲明兩個int變量,例如int l1, l2即可。 然后你將你的 function 稱為:

    twoLargest (array, l1, l2);   /* call function and output results */

其他大問題,如果用戶輸入 integer 值時出錯,您的程序將出現未定義行為 您必須驗證每個用戶輸入。 為此,您在每次輸入之后和嘗試使用由輸入填充的變量之前檢查std::cin的流狀態。 它可以是一個簡單的:

if (!(std::cin >> sizeArray)) {
    std::cerr << "error: invalid integer input.\n";
    return 1;
}

如果用戶提供了無效的sizeArray輸入,您只需退出程序。 或者,您可以進行完整的錯誤檢測和恢復,例如在何處取值來填充數組。 在這種情況下,要處理任何非整數輸入,您需要檢查.eof().bad()的流狀態標志(它們是不可恢復的錯誤)和.fail()指示非整數輸入,這您可以通過清除failbit並從stdin中刪除未讀字符來更正,然后再允許用戶重試。 你可以這樣做類似於:

    for (; i < sizeArray;) {   /* only increment on valid input */
        int n;
        std::cout << "array[" << i << "]: ";
        
        if (!(std::cin >> n)) {
            /* if eof() or bad() break read loop */
            if (std::cin.eof() || std::cin.bad()) {
                std::cerr << "(user canceled or unreconverable error)\n";
                return 1;
            }
            else if (std::cin.fail()) {     /* if failbit */
                std::cerr << "error: invalid integer input.\n";
                std::cin.clear();           /* clear failbit */
                /* extract any characters that remain unread */
                std::cin.ignore (std::numeric_limits<std::streamsize>::max(),
                                 '\n');
            }
        }
        else {  /* only on good input */
            array.push_back(n);
            i += 1;                         /* increment loop counter */
        }
    }

注意: i是在進入循環之前聲明的,因為它在我的示例中用於多種目的)

如果你把它們放在一起,你可以有一個例子來找到兩個最大的,看起來像這樣:

#include <iostream>
#include <vector>
#include <limits>

/* type of function is 'void' it does not return a value.
 * by passing references to large1 and large2 the function
 * will operate on the variable passed from main() instead
 * of local "copies" of the variables.
 */ 
void twoLargest(const std::vector<int>& arr, int& large1, int& large2)
{
    /* always initialize max variables to min of range to start */
    large1 = std::numeric_limits<int>::min();
    large2 = std::numeric_limits<int>::min();
    
    for (size_t i = 0; i < arr.size(); i++) {
        if (arr[i] > large1) {
            large2 = large1;
            large1 = arr[i];
        }
        else if (arr[i] > large2) {
            large2 = arr[i];
        }
    }
}

int main() {
    
    std::cout << "How large would you like the array to be?: ";
    int l1, l2, sizeArray, i = 0;   /* declare vars for large1/2 in main */
    /* validate EVERY user-input */
    if (!(std::cin >> sizeArray)) {
        std::cerr << "error: invalid integer input.\n";
        return 1;
    }
    
    std::vector<int> array;
    for (; i < sizeArray;) {   /* only increment on valid input */
        int n;
        std::cout << "array[" << i << "]: ";
        
        if (!(std::cin >> n)) {
            /* if eof() or bad() break read loop */
            if (std::cin.eof() || std::cin.bad()) {
                std::cerr << "(user canceled or unreconverable error)\n";
                return 1;
            }
            else if (std::cin.fail()) {     /* if failbit */
                std::cerr << "error: invalid integer input.\n";
                std::cin.clear();           /* clear failbit */
                /* extract any characters that remain unread */
                std::cin.ignore (std::numeric_limits<std::streamsize>::max(),
                                 '\n');
            }
        }
        else {  /* only on good input */
            array.push_back(n);
            i += 1;                         /* increment loop counter */
        }
    }
    
    i = 0;  /* flag controlling comma output */
    std::cout << "\nstd::vector<int>: ";
    for (const auto& n : array) {
        if (i) {
            std::cout.put(',');
        }
        std::cout << n;
        i = 1;
    }
    std::cout.put('\n');
    
    twoLargest (array, l1, l2);   /* call function and output results */
    
    std::cout << "\nresult twoLargest(): " << l1 << ", " << l2 << '\n';
}

示例使用/輸出

$ ./bin/twoLargest
How large would you like the array to be?: 5
array[0]: foo
error: invalid integer input.
array[0]: 2
array[1]: 9
array[2]: 3
array[3]: Seven, I want to enter 7!
error: invalid integer input.
array[3]: 7
array[4]: 4

std::vector<int>: 2,9,3,7,4

result twoLargest(): 9, 7

我在評論中提到了一些其他提示。 除了更正參數錯誤之外,最重要的是您需要驗證每個用戶輸入。 在你編寫了一個輸入例程后,go 嘗試並故意破壞它(用戶會錯誤地輸入錯誤的輸入並故意在你的代碼中尋找漏洞)。 如果您的輸入例程在測試時中斷——go 修復它並重試,直到您對它滿意為止。

檢查一下,如果您還有其他問題,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM