Program to check any number exist in 2D array

こ雲淡風輕ζ 提交于 2020-07-09 05:47:12

问题


I know how to check if number exist in the array, but not in a 2D array.

Please help me in 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;
}

回答1:


I know how to check if number exist in the array, but not in 2D array!

It is like you did for the one-dimensional array, instead of one, you need to now iterate through the rows and column. In another word, you need one more iteration.

#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;
         }
      }
   }
}

However, using the row size and column size like this, I will not recommend so. You should be using better std::array(if you know the size at compile time), or std::vector(if the sizes are known at run time).

For example, using std::array you could have the following code(example code). Using the range based for-loop, and a simple function makes the code more readable and less error-prone. Also, you need to know the sizes known at compile time. (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";
   }
}

In case of wondering, how to provide isIn2DArray for any arbitrary array, do it by providing the sizes as non-template parameters as below. (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!
}



回答2:


If the array is an actual 2D array, if you know how to check if a number exists in a 1D array, you can use the exact same code to determine if a value exists in a regular 2D array.

The trick is to write the code using pointers to the start and ending elements of the array. The reason why is that a 2D array stores its data in contiguous memory, no different than a 1D array.

Here is an example of the same search function working for both 1-dimensional and 2-dimensional arrays:

#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";
}

Output:

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

Surprisingly, the same function worked for 1-dimensional, 2-dimensional arrays, and even 3 dimensional arrays, all due to the data being stored in contiguous memory.

The address of the starting element, and the address of one past the ending element in the array are provided to the function, thus the function knows where to start and where to end the search.




回答3:


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;
}



回答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;
}


来源:https://stackoverflow.com/questions/62620002/program-to-check-any-number-exist-in-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!