在随机数组中查找特定数字?

时间:2018-04-03 23:16:08

标签: c++ arrays

下面是我编写的代码,用于查找100个整数数组中的最大和最小数字(随机)。

我的问题是让用户输入一个数字并找到用户输入的号码的位置。例如:“在阵列位置34处找到了数字230”或类似的东西。

我该如何解决这个问题?我的尝试看起来像

cout << "Enter #: ";
cin >> Input;
if(1){
for (int i = 0; i < 100 : i++){
if (Input == arr[i]
cout << "Location: " << i << endl;
} else
cout << "Input was not found ";



#include "stdafx.h"
#include <ctime>
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

int main() {
    int small, big;
    int arr[100];

    srand(time(0));
    for(int i=0; i < 100; i++) {
        arr[i] = rand() % 1000;
    }
    for(int i=0; i < 100; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;

    big = small = arr[0];
    for (int i = 0; i < 100; i++) {
        if (arr[i] > big) {
            big = arr[i];
        }
        if(arr[i] < small) { // compares smallest value with current element
            small = arr[i];
        }
    }
}

1 个答案:

答案 0 :(得分:0)

一个简单的(而不是理想的)解决方案是循环遍历数组,直到找到所需的数字。有点像:

const int N = 100;
int arr[N];
for (int i = 0; i < N; i++) {
    arr[i] = rand() % 1000;
}

// Number to search for
int target = 11;

// Single loop searching for target
int index = -1;
for (int i = 0; i < N; i++) {
    if (arr[i] == target) {
        index = i;
        break; // break when target found
    }
}

if (index != -1) {
    cout << "Found at " << index << "\n";
}
else {
    cout << "Not Found\n";
}

但是,您应该尽可能使用vector而不是数组。使用矢量的一个好处是能够使用标准库find函数。

#include <vector>
#include <algorithm>
#include <iostream>
#include <cstdlib>

using namespace std;

int main() {
    vector<int> vec;

    // fill vec with random numbers
    for (int i = 0; i < 100; i++) {
        int random_number = rand() % 1000;
        vec.push_back(random_number); // adds random_number to end of vec
    }

    // Number we are searching for
    int target = 7;

    // find an iterator pointing to target if it exists
    //   else it will be vec.end()
    auto it = find(vec.begin(), vec.end(), target);

    if (it != vec.end()) {
        // find distance of it from beggining of vector
        // i.e. vec[index] == target
        int index = distance(vec.begin(), it);
        cout << "Found " << target << " at " << index << "\n";
    }
    else {
         cout << "Not Found\n";
    }
}