简单的C ++数组搜索

时间:2013-11-19 23:01:11

标签: c++ arrays function

我在学校这个学期参加一个C ++课程并给了一个项目,我必须编写一个程序,要求用户输入一个数字,当他们输入0时停止,然后将数字存储到一个数组中,然后提示用户输入一个数字并在数组中搜索该数字,如果它是一个存储在数组中的数字,那么我返回“FOUND!”如果没有,我会回“未找到!” 我必须通过函数进行搜索。

除搜索功能外,我已为程序完成所有操作。我被告知要在互联网上研究如何做到这一点并将其应用到我的程序中,但问题是在这个课程中我们只被教导如何使用while()循环和我发现的每个搜索功能似乎只是重复我的因为这是一个非常基本的c ++类。

有人可以帮助我吗?

3 个答案:

答案 0 :(得分:0)

这是一个布尔函数search,它有三个参数:array,此数组的size和要搜索的target数字(我使用的是for循环):

bool search(int array[], int size, int target)
{
    for (int i = 0; i < size; ++i)
    {
        if (array[i] == target)
        {
            return true;
        }
    }

    return false;
}

然后,只要"FOUND!"分别返回"NOT FOUND!"search,您就可以打印truefalse

答案 1 :(得分:0)

该功能可以按以下方式查看

bool search( int a[], int size, int value )
{
    int i = 0;

    while ( i < size && a[i] != value ) i++;

    return ( i != size );
}

使用该功能将是以下

if ( search( YourArray, ActualNumberOfArrayElements, value ) )
{
    std::cout << "Value " << value << " found in the array" << std::endl;
}
else
{
    std::cout << "Value " << value << " did not find in the array" << std::endl;
}

答案 2 :(得分:0)

如果它真的是C ++,你应该使用C ++功能来做到这一点。首先,让我们看看该程序的完整源代码。

#include <iostream>
#include <vector>
using namespace std;

int main() {
    // Array of numbers with dynamic size
    // At first it contains 0 elements
    vector<int> haystack;

    // "Forever" loop
    for (;;) {
        // The new number
        int n;

        // Input that number.
        // Do you know that `cin >> c` returns `cin`
        // to let us write something like
        // `cin >> a >> b`? It works like
        // `(cin >> a) >> b` =>
        // `cin >> b` =>
        // `cin` which doesn't go anywhere. It's just `cin`.
        // Also, `cin` can be implicitly cast (um, I mean "transformed")
        // to `bool`. So the following line not
        // just asks for a number, but tests if
        // number input succeeded.
        if (!(cin >> n)) {
            // User pressed Ctrl+Z to end input
            // or it was something like "abc"
            // instead of a number.
            break;
        }
        if (n == 0) {
            // User gave us zero.
            break;
        }

        // Add new element in an array,
        // save `n` in it
        haystack.push_back(n);
    }

    // Number we will search in that array
    int needle;
    cin >> needle;

    /////////////////////////////////////////////////////////
    // Easy way:
    /////////////////////////////////////////////////////////

    // Here's a boolean flag.
    // `true` value in it means that we've currently found
    //        the number
    // `false` means that we still didn't found it
    bool found = false;

    // Iterate over all numbers we've recently got
    // `haystack.size()` is a quantity of that numbers
    // Call to `size()` takes more time than reading value
    // from a variable, so we'd better save it in a variable `ilen`.
    // `size()` returns value of `size_t` type. It's usually an
    // integer without a sign.
    for (size_t i = 0, ilen = haystack.size(); i < ilen; ++i) {
        // Test if i-th number is the one we search for
        if (haystack[i] == needle) {
            // Yay, it is! Set the flag to true.
            found = true;
            // Exit loop, as we don't care for all the other values
            break;
        }
    }

    // Don't ever write `found == true` to test if boolean flag is true.
    // ==, != and other comparison operators do return boolean values.
    if (found) {
        cout << "FOUND" << endl;
    } else {
        cout << "NOT FOUND" << endl;
    }
    // Also you could write it with ternary operator ("short if")
    // cout << (found ? "FOUND" : "NOT FOUND") << endl;

    /////////////////////////////////////////////////////////
    // Harder ways
    /////////////////////////////////////////////////////////

    // You could iterate over items in that array like
    // for (vector<int>::const_iterator it = haystack.begin(),
    //      iend = haystack.end(); it != iend; ++it) {
    //     if (*it == needle) { ... }
    //}
    // It's kinda hardcore, but performs well.

    // You could even go nuts and use some stuff from
    // <algorithm> header
    // if (find(haystack.begin(), haystack.end(), needle) !=haystack.end()) {
    //     cout << "FOUND" << endl;
    // } else {
    //     cout << "NOT FOUND" << endl;
    // }
    // Look, ma, no loops!
}