我正在尝试在C++中制作一个程序,该程序将使用单独的搜索函数在大小为 10 的数组中搜索所需的值。 下面是代码:
主.cpp
#include <iostream>
#include <array>
using namespace std;
int main()
{
cout << "Welcome to the array linked list program.";
int sanadA[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int d = 0;
cin >> d;
while (d =! 0)
{
cout << "Number to be found";
cin >> d;
bool found = seqSearch1(sanadA, 10, d, -1);
cout << found;
}
}
seqSearch1.cpp
#include <iostream>
using namespace std;
bool jw_search (int *list, int size, int key, int*& rec)
{ //Basic sequential search.
bool found = false;
int i;
for(i=0;i<size;i++)
{
if (key == list[i])
{
break;
}
if (i < size)
{
found = true;
rec = &list[i];
}
}
return found;
}
我收到错误:
C:\Users\tevin\Documents\sanad\main.cpp|13|warning:建议将赋值括为真值 [-Wparentheses]|
C:\Program Files (x86(\CodeBlocks\MinGW\lib\gcc\mingw32\5.1.0\include\c++\bits\c++0x_warning.h|32|error: #error 此文件需要 ISO C++ 2011 标准的编译器和库支持。此支持目前处于实验阶段,必须使用 -std=c++11 或 -std=gnu++11 编译器选项启用。|
C:\Users\tevin\Documents\sanad\main.cpp|19|error: 'seqSearch1' 未在此范围内声明|
我需要帮助弄清楚为什么会发生这种情况。
我假设错误发生在这一行:
bool found = seqSearch1(sanadA, 10, d, -1);
问题是您尚未声明任何名为seqSearch1()
的函数。相反,您有一个名为jw_search()
的函数。因此,您可以将该行更改为:
bool found = jw_search(sanadA, 10, d, -1);
但是您还需要一个名为seqSearch1.h
的头文件,其中包含以下行:
bool jw_search (int *list, int size, int key, int*& rec);
最后将这一行添加到main.cpp
的顶部:
#include "seqSearch1.h"
编译代码时,需要在命令中包含所有源文件。例如,如果您使用的是g++
,则可以执行以下操作:
g++ main.cpp seqSearch1.cpp
若要了解其工作原理,需要了解头文件以及函数声明和函数定义之间的区别。还应了解编译器和链接器之间的区别。
Code-Apprentice可以直接回答您的问题。如果您希望代码位于多个文件中,则需要 seqSearch1 函数的声明是 main.cpp或通过 #include 指令包含
代码存在多个问题。 我已经为您修复了一下,并将其放在一个文件中。
#include <iostream>
#include <array>
using namespace std;
bool seqSearch1 (int *list, int size, int key, int& rec)
{//Basic sequential search.
bool found = false;
int i;
for(i=0;i<size;i++)
{
if (key == list[i])
{
found = true;
rec = i;
break;
}
}
return found;
}
int main()
{
cout << "Welcome to the array linked list program." << endl;
int sanadA[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int d = -1;
while (d != 0)
{
cout << "Number to be found, 0 to end?";
cin >> d;
if(d == 0) break;
int index = -1;
bool found = seqSearch1(sanadA, 10, d, index);
if(found) cout << "Found" << endl;
else cout << "Not Found" << endl;
}
}
几个问题:
引用- 了错误的函数。
- 循环结构很混乱。
- seqSearch1 的第四个参数存在类型混淆。