這是我的代碼我想嘗試將我的陣列與數字進行比較,但基本上我給了我一些錯誤,我試圖通過線性搜索找到一個數字并在 C 中列印該數字的索引
// linear search
#include <iostream>
using namespace std;
int search(int arr, int n, int x)
{
int i=0;
for (i = 0; i < n; i ){
if (arr[i] == x){
return i;}
}
return -1;
}
// Driver code
int main(void)
{
int size;
int temp;
cout << "Enter Size of Arry";
cin >> size;
int arr[size];
for(int i=0;i<size;i ){
cout << "Enter a " << i << "Element of your arry : ";
cin >> temp;
arr[i]=temp;
}
cout << "Enter the number that you will find index";
int x;
cin >> x;
// Function call
int result = search(arr, size, x);
(result == -1)
? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
這是錯誤
PS C:\Users\talha\OneDrive\Desktop\Study_Material\DSA_lab\cs201149_lab1_3C> g Q1.cpp -o Q11.exe
Q1.cpp: In function 'int search(int, int, int)':
Q1.cpp:9:12: error: invalid types 'int[int]' for array subscript
if (arr[i] == x){
^
Q1.cpp: In function 'int main()':
Q1.cpp:35:34: error: invalid conversion from 'int*' to 'int' [-fpermissive]
int result = search(arr, size, x);
^
Q1.cpp:5:5: note: initializing argument 1 of 'int search(int, int, int)'
int search(int arr, int n, int x)
^~~~~~
PS C:\Users\talha\OneDrive\Desktop\Study_Material\DSA_lab\cs201149_lab1_3C>
uj5u.com熱心網友回復:
首先在 C 中,陣列的大小必須是編譯時常量。因此,以以下代碼片段為例:
int n = 10;
int arr[n]; //INCORRECT because n is not a constant expression
正確的寫法是:
const int n = 10;
int arr[n]; //CORRECT
同樣,以下(您在代碼示例中所做的)不正確:
int size;
int temp;
cout << "Enter Size of Arry";
cin >> size;
int arr[size];//INCORRECT because variable size is not a constant expression
您應該std::vector為您的目的使用,如下所示:
#include <iostream>
#include <vector>
using namespace std;
//the first argument is a vector<int>
int search(std::vector<int> arr, int x)
{
int i=0;
for (i = 0; i < arr.size(); i ){//use size()member function
if (arr[i] == x){
return i;}
}
return -1;
}
// Driver code
int main(void)
{
int size;
int temp;
cout << "Enter Size of Arry";
cin >> size;
//create a vector instead of an array
std::vector<int> arr(size);
for(int i=0;i<arr.size();i ){//use the size member function
cout << "Enter a " << i << "Element of your arry : ";
cin >> temp;
arr[i]=temp;
}
cout << "Enter the number that you will find index";
int x;
cin >> x;
// Function call
int result = search(arr, x);//no need to pass the size of the vector
(result == -1)
? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
請注意,您也可以使用std::find而不是撰寫自己的搜索演算法。
uj5u.com熱心網友回復:
對于像這樣的初學者可變長度陣列
int arr[size];
不是標準的 C 功能。相反,std::vector<int>在 C 程式中使用標準容器會好得多。
其次,函式宣告不正確。第一個引數被宣告為具有 int 型別。
int search(int arr, int n, int x)
您需要通過以下方式宣告該函式
int search(int arr[], int n, int x)
或等效地
int search(int *arr, int n, int x)
請注意,std::find在 C 中有標準演算法來執行在容器中搜索元素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/367582.html
下一篇:如何從每個索引中獲取值?
