C++ 2차원 벡터 예시 2

오현진·2024년 6월 14일

C++ 

목록 보기
4/26
  • 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)); // 첫 번째 행에 4개의 원소 추가, 초기값 1
    array.push_back(vector<int>(3, 2)); // 두 번째 행에 3개의 원소 추가, 초기값 2
    array.push_back(vector<int>(5, 3)); // 세 번째 행에 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 

0개의 댓글