mardi 7 juillet 2020

Shifting value i multi dimensional array C++

I want to shift value in multi dimensional array, i try but its not working at all and am also confused within logic.

here what i want to do

    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}

and let i pass 1, 2 so it should delete 5 from array and shift all elements. Expected Output:

    1, 2, 3,
    4, 6, 7,
    8, 9, 0

Here is my code.

    #include <iostream>

void display(int arr[][3], int size)
{
  std::cout << "\nDisplay of array:\n";
  for (int i = 0; i < size; i++) {
    for (int j = 0; j < size; j++) {
      std::cout << i << " " << j  << " : " << arr[i][j] << std::endl;
    }
  }
  return;
}
void insert(int arr[][3], int size)
{
  std::cout << "\nInserting element in an array:\n";
  int pos, num;
  std::cout << "Enter  new value to be inserted: ";
  std::cin >> num;
  std::cout << "Enter the position where you wanted to inserted it: ";
  std::cin >> pos;

  /*for (int i = size - 2; i >= pos; i--) {
    arr[i+1] = arr[i];
  }*/
  //arr[pos] = num;
  display(arr, size);
}
void delete_ele(int arr[][3], int size)
{
  std::cout << "\nDeleting an array:\n";
  int posX, posY;
  display(arr, size);
  std::cout << std::endl;
  std::cout << "Enter the X pos where you wanted to delete element: ";
  std::cin >> posX;
  std::cout << "Enter the Y pos where you wanted to delete element: ";
  std::cin >> posY;
  const int s = 3;
  int newArr[s][s];
  int x = 0, y = 0;
  bool t = false;
  for (int i = 0; i < size; i++) {
      for (int j = 0; j < size; j++) {
        if (i == posX && j == posY) {
          t = true;
          continue;
        }
        newArr[x][y] = arr[i][j];
        y++;
      }
      if (t) {
        continue;
      }
      x++;
  }

  display(newArr, size);
}
int main(void)
{
  // size of array.
  const int size = 3;

  //Decleration of arrays
  int arr[size][size] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
  };
  int arr2[size][size] = {
    {1, 2, 3},
    {7, 8, 9}
  };

  // Delete an array basse on position.
  delete_ele(arr, size);
  // Insert an array by shifting..
  insert(arr2, size);
  return 0;
} // end of main.

Thanks

Aucun commentaire:

Enregistrer un commentaire