C++容器嵌套實現動態二維數組(Vector2D)


轉: http://blog.csdn.net/Touch_Dream/article/details/74931891

#include<stdio.h> #include <iostream> #include <vector> using namespace std; int main() { int row, column; cin >> row >> column; vector<vector<int> > a(row, vector<int>(column)); //row決定最里面層容器大小,vector<int>(column)決定外層容器的類型和大小 for (int j = 0; j < row; j++) for (int k = 0; k< column; k++) a[j][k] = rand() % 100; for (int j = 0; j < row; j++) { cout << endl; for (int k = 0; k< column; k++) { a[j][k] = rand() % 100; cout << a[j][k] << " "; } } while (1) { } return 0; }

方法二

利用vector的成員函數resize,來制定大小

#include<stdio.h> #include <iostream> #include <vector> using namespace std; int main() { int row, column; cin >> row ; vector<vector<int> > a(row);//row決定最里面層容器大小,vector<int>(column)決定外層容器的類型和大小 for (int k = 0; k < row; k++) a[k].resize(row);//row*row矩陣 //使用空間 for (int j = 0; j < row; j++) for (int k = 0; k< row; k++) a[j][k] = rand() % 100; for (int j = 0; j < row; j++) { cout << endl; for (int k = 0; k< row; k++) { a[j][k] = rand() % 100; cout << a[j][k] << " "; } } while (1) { } return 0; }

測試結果

這里寫圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM