- rows x cols 크기의 2차원 배열을 동적으로 생성하고 초기화한 뒤, 각 요소를 출력하는 예제
#include <vector>
#include <iostream>
using namespace std;
int main() {
int rows = 3;
int cols = 4;
vector<vector<int>> array(rows, vector<int>(cols));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
array[i][j] = i * cols + j + 1;
}
}
for (const auto& row : array) {
for (int elem : row) {
cout << elem << " ";
}
cout << endl;
}
return 0;
}
1 2 3 4
5 6 7 8
9 10 11 12
- 빈 2차원 벡터를 선언한 후, 각 행에 다른 크기의 벡터를 추가하고 초기값을 설정한 뒤, 각 요소를 출력하는 예제
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<vector<int>> array;
array.push_back(vector<int>(4, 1));
array.push_back(vector<int>(3, 2));
array.push_back(vector<int>(5, 3));
for (const auto& row : array) {
for (int elem : row) {
cout << elem << " ";
}
cout << endl;
}
return 0;
}
1 1 1 1
2 2 2
3 3 3 3 3