Переписать все элементы двумерного массива в одномерный

Уровень сложности:

Задана матрица А размерностью nxm. Записать все элементы матрицы в одномерный массив.

Предлагаю для решения этой задачи организовать заполнение массива случайными числами. Это сократит время на ввод элементов двумерного массива. Вся сложность данного задания состоит в том, что каким-то образом нужно преобразовать двумерный массив в одномерный. Как это сделать? Легко!

Наша задача создать одномерный массив, в котором могут поместиться все элементы двумерного. Для этого определяем размер двумерного массива, умножаем количество строк на количество столбцов. Далее динамически выделяем  память под одномерный массив. Используя несколько циклов for заполняем одномерный массив и выводим на экран. Результат работы программы показан ниже:

// matrica_A.cpp: определяет точку входа для консольного приложения.

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

int main(int argc, char* argv[])
{
    srand(time(NULL));
    setlocale(LC_ALL, "rus");
    int number_rows,// строки
        number_columns; // столбцы
    cout << "Введите количество строк матрицы: ";
    cin >> number_rows;
    cout << "Введите количество столбцов матрицы: ";
    cin >> number_columns;

    // динамическое создание двумерного массива
    int **arrayPtr = new int* [number_rows];
    for (int count = 0; count < number_rows; count++)
        arrayPtr[count] = new int [number_columns];

    for (int counter_rows = 0; counter_rows < number_rows; counter_rows++)
    {
        for (int counter_columns = 0; counter_columns < number_columns; counter_columns++)
        {
            arrayPtr[counter_rows][counter_columns] = rand() % 100; // заполнение массива случайными числами
            cout << setw(2) << arrayPtr[counter_rows][counter_columns] << "  "; // вывод на экран двумерного массива
        }
        cout << endl;
    }
    cout << endl;

    int *vectorPtr = new int [number_rows * number_columns]; // создание одномерного динамического массива 
    int vector_counter = 0; // переменная-индекс для одномерного массива

    for (int counter_rows = 0; counter_rows < number_rows; counter_rows++)
    {
        for (int counter_columns = 0; counter_columns < number_columns; counter_columns++)
        {
            vectorPtr[vector_counter] = arrayPtr[counter_rows][counter_columns]; // записываем элементы матрицы в одномерный массив
            cout << vectorPtr[vector_counter] << "  "; // печать элементов одномерного массива
            vector_counter++; // инкремент индекса
        }
    }

    delete [] vectorPtr; // высвобождение памяти, отводимой под одномерный массив

    // удаление двумерного динамического массива
    for (int count = 0; count < number_rows; count++)
        delete []arrayPtr[count];
    cout << endl;
    system("pause");
    return 0;
}

Результат:

CppStudio.com

Введите количество строк матрицы: 3
Введите количество столбцов матрицы: 5
4 46 83 2 79
78 49 65 52 73
94 98 61 4 82

4 46 83 2 79 78 49 65 52 73 94 98 61 4 82

Следующие статьи помогут вам в решении данной задачи:
Автор: admin
Дата: 12.09.2012
Поделиться:

Комментарии

  1. Роман Максимов

    /*
      Заданна матрица А размерностью NxM. Записать все элеиенты матрицы в
      одномерный массив.
    */
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <iomanip>
    //---------------------------------------------------------------------------
    using namespace std;
    //---------------------------------------------------------------------------
    int main()
    {
      int columns, 
          rows,
          **matrix,
          *array;
    
      cout << "Enter the number of rows in the matrix: ";
      cin >> rows;
    
      cout << "Enter the number of columns in the matrix: ";
      cin >> columns;
    
      try {
        matrix = new int*[rows];
        for (int i = 0; i < rows; i++)
          matrix[i] = new int[columns];
    
        array = new int[rows * columns];
      } catch (bad_alloc) {
        cout << "Unable to allocate memory." << endl;
        system("pause");
        return 1;
      }
    
      srand(time(NULL));
    
      for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
          array[i * columns + j] = matrix[i][j] = rand() % 100;
    
          cout << setw(2) << matrix[i][j] << " ";
        }
    
        cout << endl;
      }
    
      cout << endl;
    
      for (int i = 0; i < rows * columns; i++)
        cout << array[i] << " ";
    
      cout << endl;
    
      for (int i = 0; i < rows; i++)
        delete [] matrix[i];
    
      delete [] matrix;
    
      delete [] array;
    
      system("pause");
      return 0;
    }
    //---------------------------------------------------------------------------
    
    
  2. Anufree

    #include <iostream>
    #include <conio.h>
    #include <random>
    #include <time.h>
    
    using namespace std;
    
    int main()
    {
    	setlocale(LC_ALL, "Russian");
    
    	int **A_Arr;
    	int *B_Arr;
    	int N, M;
    	int counter = 0;
    
    	cout << "Укажите кол-во колонок: "; cin >> N;
    	cout << "Укажите кол-во строк: "; cin >> M;
    
    	A_Arr = new int *[N];
    	for(int i(0); i < N; i++)
    		A_Arr[i] = new int [M];
    
    	B_Arr = new int [N * M];
    
    	srand((int)time(0));
    
    	for(int i(0); i < N; i++)
    	{
    		for(int j(0); j < M; j++)
    		{
    			cout << (A_Arr[i][j] = rand() % 101) << ' ';
    			B_Arr[counter] = A_Arr[i][j];
    			counter++;
    		}
    		cout << endl;
    	}
    
    	for(int i(0); i < N * M; i++)
    	{
    		cout << B_Arr[i] << ' ';
    	}
    
    	delete []B_Arr;
    	B_Arr = NULL;
    
    	for(int i(0);i < N; i++) 
    		delete []A_Arr[i];
    	delete []A_Arr;
    	A_Arr = NULL;
    
    	_getch();
    	
    	return 0;
    }
  3. Vladimir Belikov

    #include <iostream>
    #include <stdlib.h>
    using namespace std;
    
    int main()
    {
      srand(time(NULL));
      unsigned short x = 0, y = 0, counter = 0;
      cout << "Введите длину и ширину матрицу через пробел: ";
      cin >> x; cin >> y;
      short arr2d[x][y];
      cout << "Сгенерированый массив:" << '\n';
      for (unsigned short q = 0; q < x; ++q)
      {
        for (unsigned short w = 0; w < y; ++w)
        {
          arr2d[q][w] = rand() % 100;
          cout << arr2d[q][w] << ' ';
        }
        cout << '\n';
      }
      cout << "Размер одномерного массива: " << x * y << '\n';
      short * arr = new short [x * y];
      for (unsigned short q = 0; q < x; ++q)
        for (unsigned short w = 0; w < y; ++w)
          arr[counter++] = arr2d[q][w];
      cout << "Одномерный массив:" << '\n';
      for (unsigned short q = 0; q < x * y; ++q)
        cout << arr[q] << ' ';
      delete [] arr;
      return 0;
    }
  4. Максим Костюков

    //Преобразование матрица->вектор
    //17.04.16 by Nintemoder
    //QtCreator
    #include <iostream>
    #include <cstdlib>
    #include <ctime>
    
    using namespace std;
    
    int main(int argc, char *argv[])
    {
        srand(time(NULL));
        int n,m;
        cout<<"Size of matrix:";
        cin>>n>>m;
        int** matrix=new int*[n];
        for(int i=0;i<n;i++)
            matrix[i]=new int[m];
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
                matrix[i][j]=rand()%100;
        cout<<"Generating matrix...Done!"<<endl;
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++)
                cout<<matrix[i][j]<<' ';
            cout<<endl;}
        int* a=new int[n*m];
        int index=0;
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++,index++)
            a[index]=matrix[i][j];
        cout<<"Converting matrix to array...Done!"<<endl;
        for(int i=0;i<m*n;i++)cout<<a[i]<<' ';
        cout<<endl;
        return 0;
    }

Оставить комментарий

Вы должны войти, чтобы оставить комментарий.