未在此范围内声明的变量数组线性搜索

时间:2018-08-13 01:23:33

标签: c++ algorithm search linear

我试图用C ++编写一个程序,使用单独的搜索功能在大小为10的数组中搜索所需的值。下面是代码:

main.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 |警告:建议在赋值周围使用括号作为真值[-Wparentheses] |

     

C:\ Program Files(x86)\ CodeBlocks \ MinGW \ lib \ gcc \ mingw32 \ 5.1.0 \ include \ c ++ \ bits \ c ++ 0x_warning.h | 32 |错误:#error此文件需要编译器和库支持ISO C ++ 2011标准。此支持目前处于试验阶段,必须使用-std = c ++ 11或-std = gnu ++ 11编译器选项启用。|

     

C:\ Users \ tevin \ Documents \ sanad \ main.cpp | 19 |错误:未在此范围内声明'seqSearch1'|

我需要帮助弄清楚为什么会这样。

2 个答案:

答案 0 :(得分:3)

我认为此行发生错误:

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

要了解其工作原理,您需要了解头文件以及函数声明和函数定义之间的区别。您还应该了解编译器和链接器之间的区别。

答案 1 :(得分:1)

代码学徒可以直接回答您的问题。如果要将代码放在多个文件中,则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;
}
}

几个问题:

  1. 该函数的名称错误。
  2. 循环结构令人困惑。
  3. seqSearch1的第四个参数类型混乱。