【问题标题】:Program to check any number exist in 2D array检查二维数组中是否存在任何数字的程序
【发布时间】:2020-10-18 13:06:58
【问题描述】:

我知道如何检查数字是否存在于数组中,但不存在于 二维数组中

请在 2D 中帮助我。

#include<iostream>
using namespace std;

int main()
{
   int a[3] = { 4,5,6 };
   int b, c;
   int x = 1, fact = 1;

   cout << "enter no ";
   cin >> b;

   for (int i = 0; i < 3; i++) 
   {
      if (b == a[i]) {
         c = a[i];
         break;
      }
   }
   cout << "no entered is present" << endl;
}

【问题讨论】:

  • 你真的知道如何检查一维数组吗?无论输入的值是否存在于数组中,您发布的代码都将打印“没有输入”。
  • 这里没有二维数组!
  • @MikeCAT 'no' 代表这个程序中的数字
  • @AishaRazzaq 那么应该防止输入的数字不在数组中的时候打印吧?
  • 您的问题中的二维数组在哪里?

标签: c++ loops c++11 multidimensional-array data-structures


【解决方案1】:

我知道如何检查数组中是否存在数字,但二维数组中不存在!

就像您对一维数组所做的那样,您现在需要遍历行和列,而不是一维数组。换句话说,您需要再进行一次迭代。

#include<iostream>

int main()
{
   int a[2][3]{ { 1,2,3 }, { 4,5,6 } };
   int userInput = 5;
   bool found = false;
   for (int row = 0; !found && row < 2; ++row) // if not found and row size < 2
   {
      for (int col = 0; col < 3; ++col)  // if column size < 3
      {
         if (userInput == a[row][col])   // access the element like this
         {
            // other codes
            std::cout << "No entered is present\n";
            found = true;
            break;
         }
      }
   }
}

但是,像这样使用行大小和列大小,我不建议这样做。您应该使用更好的std::array(如果您在编译时知道大小)或std::vector(如果在运行时知道大小)。

例如,使用std::array,您可以拥有以下代码(示例代码)。使用 range based for-loop 和一个简单的函数可以使代码更具可读性且不易出错。此外,您需要知道编译时已知的大小。 (See live demo)

#include <iostream>
#include <array> // std::array

bool isIn2DArray(const std::array<std::array<int, 3>, 2>& arr, int val) /* noexcept */
{
   // range based for-loop instead of index based looping
   for (const std::array<int, 3> & row : arr)
      for (const int element : row)
         if (element == val)
            return true;    // if found in the array, just return the boolean!
   return false;  // if not found!
}

int main()
{
   std::array<std::array<int, 3>, 2> a{ { { 1,2,3 }, { 4,5,6 } }  };
   int userInput = 5;
   if (isIn2DArray(a, userInput))  // you call the function like this!
   {
      std::cout << "Found in the array!\n";
   }
   else
   {
      std::cout << "Didn't find!\n";
   }
}

如果想知道如何为任意数组提供isIn2DArray,请提供non-template parameters 的大小,如下所示。 (See live demo)

#include <array> // std::array

template<std::size_t Row, std::size_t Col>
bool isIn2DArray(const std::array<std::array<int, Col>, Row>& arr, int val)/* noexcept */
{
   // range based for-loop instead of index based looping
   for (const std::array<int, 3> & row : arr) 
      for (const int element : row)
         if (element == val)
            return true;    // if found in the array, just return the boolean!
 
   return false;  // if not found!
}

【讨论】:

  • 实际上,您只需要一次迭代,因为二维数组将其数据存储在连续内存中。
  • 内循环中的 break; 不会破坏外循环。
  • @PaulMcKenzie 没错,但对于像 OP 这样的初学者来说,应该很容易掌握旧循环。
  • @MikeCAT 那是个错误。我应该去找一个函数,如果找到匹配项就返回。更正并谢谢,顺便说一句!
【解决方案2】:
bool check2dArray(vector<vector<int>> mat, int n){
    int rows = mat.size();
    if (rows==0) return false;
    int cols = mat[0].size();
    for (int i=0; i<rows; i++){
        for (int j=0; j<cols; j++){
            if (n == mat[i][j]) return true;
        }
    }
    return false;
}

【讨论】:

    【解决方案3】:

    如果数组是一个实际的二维数组,如果您知道如何检查一个数字是否存在于一维数组中,您可以使用完全相同的代码来确定一个值是否存在于常规二维数组中。

    诀窍是使用指向数组开始和结束元素的指针编写代码。原因是二维数组将其数据存储在连续内存中,与一维数组没有什么不同。

    下面是一个适用于一维和二维数组的相同搜索函数的示例:

    #include<iostream>
    
    bool exists(int *start, int *end, int value)
    {
       while (start != end)
       {
          if ( value == *start )
            return true;
          ++start;
       }
       return false;
    }
    
    int main() 
    {
        int a[3] =  {4,5,6};
        bool found = exists(a, a + 3, 5);
        if ( found )
           std::cout << "The number 5 was found\n";
        else
           std::cout << "The number 5 was not found\n";
    
        // now a 2d array
        int a2[3][4] = {{1,2,3,4},{7,8,9,10},{2,43,2,0}};
        found = exists(&a2[0], &a2[2][4], 43);
        if ( found )
           std::cout << "The number 43 was found\n";
        else
           std::cout << "The number 43 was not found\n";
    
        found = exists(&a2[0][0], &a2[2][4], 11);
        if ( found )
           std::cout << "The number 11 was found\n";
        else
           std::cout << "The number 11 was not found\n";
    
        // Let's try a 3D array for fun  
        int a3[2][3][4] = {{{1,2,3,4},{7,8,9,10},{2,43,2,0}},
                           {{6,9,1,56},{4,8,2,10},{2,43,2,87}}};
    
        found = exists(&a3[0][0][0], &a3[1][2][4], 56);
        if ( found )
           std::cout << "The number 56 was found\n";
        else
           std::cout << "The number 56 was not found\n";
    }
    

    输出:

    The number 5 was found
    The number 43 was found
    The number 11 was not found
    The number 56 was found
    

    令人惊讶的是,相同的函数适用于 1 维、2 维数组,甚至 3 维数组,这都是因为数据存储在连续内存中。

    数组中起始元素的地址和结束元素的地址被提供给函数,因此函数知道从哪里开始和在哪里结束搜索。

    【讨论】:

    • 最好有一个演示程序(使用单次迭代)。很好的解释。 +1
    【解决方案4】:
    template <class Matrix, class CheckValue>
    bool CheckExists(const Matrix& M, const CheckValue& Value) {
        for (const auto& m : M)
            for (const auto& v : m)
                if (v == Value)
                    return true;
    
        return false;
    }
    
    int main(int, char**)
    {
        int cArray[10][100]; auto exists = CheckExists(cArray, 10);
        std::vector<std::vector<int>> vec; exists = CheckExists(vec, 0);
        std::array<std::array<int, 10>, 100> arr; exists = CheckExists(arr, 0);
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      • 1970-01-01
      相关资源
      最近更新 更多