[英]I'm having trouble with my function for finding the lowest value in a 5x5 two dimensional array
#include <iostream>
#include <vector>
#include <ctime>
#include <stdlib.h>
using namespace std;
void displayArray(int elements[][5], int numCol, int numRow) {
for (int row = 0; row < numRow; row++) {
for (int col = 0; col < numCol; col++) {
cout << elements[row][col] << " ";
}
cout << endl;
}
}
int findMin(int arr[], int n) {
int mini = arr[0];
for (int i = 0; i < n; i++) {
if (arr[i] < mini) {
mini = arr[i];
}
return { mini };
}
}
int findMax(int arr[], int n) {
int maxi = arr[0];
for (int i = 0; i < n; i++) {
if (arr[i] > maxi) {
maxi = arr[i];
}
}
return { maxi };
}
int main()
{
const int numCol = 5;
const int numRow = 5;
int elements[numCol][numRow] = { { 81, 27, 83, 89, 92}, {87, 76, 84, 98, 99}, {83, 47, 89, 42, 48}, {75, 96, 76, 34 ,38}, {98, 83, 76, 27, 29} };
int N = sizeof(elements) / sizeof(elements[0]);
displayArray(elements, numCol, numRow);
cout << "Minimum is: " << findMin(elements, N);
}
所以目前,在執行此代碼時,我收到一個錯誤,指出我的參數不兼容 C++ 類型的參數與類型的參數不兼容。 我目前不知道為什么會遇到這個問題。 我的假設是,我不能用普通數組做到這一點,並且可能必須使用向量數組才能實現在數組中產生最小數字和最大數字的最終目標。
由於二維 arrays 有一個連續的 memory 布局,它們實際上是一維 arrays 在引擎蓋下。
因此,您仍然可以調用您的findMin
和findMax
函數而不更改它們的簽名。 訣竅是傳遞二維數組的第一個元素的地址:
int findMin(int arr[], int n)
{
//...
}
int main()
{
const int numCol = 5;
const int numRow = 5;
int elements[numCol][numRow] = { { 81, 27, 83, 89, 92}, {87, 76, 84, 98, 99}, {83, 47, 89, 42, 48}, {75, 96, 76, 34 ,38}, {98, 83, 76, 27, 29} };
int N = sizeof(elements) / sizeof(elements[0]);
displayArray(elements, numCol, numRow);
// Note that we are using the address of the first item
cout << "Minimum is: " << findMin(&elements[0][0], N);
}
第二個問題是你的findMin
function 是錯誤的。 您過早返回,而不是在for
循環完成后返回。
不要做所有這些工作,而是使用std::min_element
:
#include <algorithm>
//...
int findMin(int arr[], int n)
{
return *std::min_element(arr, arr + n);
}
與findMax
相同,除了使用std::max_element
:
#include <algorithm>
//...
int findMax(int arr[], int n)
{
return *std::max_element(arr, arr + n);
}
請注意,沒有使用std::vector
——一切都使用了原始的二維數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.