1 // #include<bits/stdc++.h> 2 #include<iostream> 3 #include<vector> 4 using namespace std; 5 int main() { 6 int n; 7 cin >> n; 8 // write your code here...... 9 10 // // 1.使用一维数组模拟 11 // int* num = new int[n * n]; 12 // for (int i = 0; i < n; i++) { // 赋值 13 // for (int j = 0; j < n; j++) 14 // num[i * n + j] = i + j; 15 // } 16 // for (int i = 0; i < n; i++) { // 输出 17 // for (int j = 0; j < n; j++) 18 // cout << num[i * n + j] << ' '; 19 // cout << endl; 20 // } 21 // delete [] num; // !!!记得释放内存!!! 22 23 24 // // 2.指针数组: 25 // int** num = new int* [n]; 26 27 // for (int i = 0; i < n; i++) // !!!! 分别申请内存 !!!! 28 // num[i] = new int[n]; 29 30 // for (int i = 0; i < n; i++) // 赋值 31 // for (int j = 0; j < n; j++) 32 // num[i][j] = i + j; 33 // for (int i = 0; i < n; i++) //输出 34 // { 35 // for (int j = 0; j < n; j++) 36 // cout << num[i][j] << ' '; 37 // cout << endl; 38 // } 39 40 // for (int i = 0; i < n; i++) // !!!! 释放每一行的内存 !!!! 41 // delete [] num[i]; 42 // delete [] num; // !!!! 释放指向行的指针数组的内存 !!!! 43 44 45 // 3.vector容器嵌套 46 vector<vector<int>> num(n, vector<int>(n)); // 大小n*n,初始值全为0 47 for (int i = 0; i < n; i++) { // 赋值 48 for (int j = 0; j < n; j++) { 49 num[i][j] = i + j ; 50 } 51 } 52 53 // // 一.for嵌套遍历 54 // for (int i = 0; i < n; i++) { 55 // for (int j = 0; j < n; j++) 56 // cout << num[i][j] << ' '; 57 // cout << endl; 58 // } 59 60 // 二.迭代器遍历: 61 for(auto row = num.begin(); row != num.end(); ++row) 62 { 63 // for(auto element = row->begin(); element != row->end(); ++element) 64 // cout << *element << ' '; 65 // cout << endl; 66 67 for(auto element : *row) 68 cout << element << ' '; 69 cout << endl; 70 } 71 72 return 0; 73 }
标签:cout,int,创建,++,二维,num,数组,include From: https://www.cnblogs.com/threefourfour/p/18192668