码迷,mamicode.com
首页 > 编程语言 > 详细

C++中动态申请二维数组

时间:2014-08-26 15:31:46      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:c++   动态数组   

这里主要介绍C++中动态申请二维数组的两种方式,直接给出代码,很容易明白,简单的作为一个笔记。

#include <iostream>
#include <iomanip>         // 输入输出操纵  
#include <vector>
using namespace std;


// 法一:new 方式申请
void dynamicArray()
{
	int rows, cols;
	cin >> rows >> cols;
	int **element = new int* [rows];    // 申请二维动态数组
	int i;
	for (i = 0; i < rows; i++)
		element[i] = new int[cols];

	int j;
	for(i = 0; i < rows; i++)               // 初始化
	{
		for (j = 0; j < cols; j++)
		{
			cin >> element[i][j];		
		}
	}
	for (i = 0; i < rows; i++)
	{
		for(j = 0; j < cols; j++)
		{
			cout << setw(4) << element[i][j];   // 每个输出占四个字符,前面以空格填充
			//cout << setfill('*') << element[i][j];  // 空格以*填充
		}
		cout << endl;
	}

	for(i = 0; i < cols; i++) // 释放动态数组
	{
		delete []element[i];
	}
	delete []element;

}

// 法二:vector 方式  没用new无需释放
void dynamicArray2()
{
	int rows, cols;
	cin >> rows >> cols;
	vector<vector<int>> element(rows, vector<int>(cols));  // 用vector申请二维动态数组
	int i,j;
	for(i = 0; i < rows; i++)               // 初始化
	{
		for (j = 0; j < cols; j++)
		{
			cin >> element[i][j];		
		}
	}
	for (i = 0; i < rows; i++)
	{
		for(j = 0; j < cols; j++)
		{
			cout << setw(4) << element[i][j];   // 每个输出占四个字符,前面以空格填充
			//cout << setfill('*') << element[i][j];  // 空格以*填充
		}
		cout << endl;
	}

}

参考blog:1:http://www.cnblogs.com/China3S/p/3616938.html

2:http://blog.sina.com.cn/s/blog_afe2af380101b4gz.html

C++中动态申请二维数组

标签:c++   动态数组   

原文地址:http://blog.csdn.net/lu597203933/article/details/38847641

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!