C++ 1, 2차원 vector 선언 및 함수로 인자 전달 후 출력

1. 정리

vector는 크기를 바꿀 수 있는 동적 배열이다. 배열처럼 인덱스로 접근할 수 있고, 요소 추가와 삭제도 간단하게 처리한다.




1차원 vector와 2차원 vector를 선언한 뒤 함수에 전달해 출력하는 예제를 정리한다.

vector<string> v_11 = { "a", "b", "c" };
vector<vector<string>> v_22 = {
    {"a", "aa"},
    {"b", "bb"},
    {"c", "cc"}
};




2. 1차원 vector 출력

vector를 값으로 전달하면 복사본이 만들어진다. 읽기만 할 때는 const 참조로 전달하면 불필요한 복사를 피할 수 있다.

void print_v_11(const vector<string>& v_11) {
    for (const auto& value : v_11) {
        cout << value << endl;
    }
}




3. 2차원 vector 출력

2차원 vector는 바깥 vector를 행으로, 안쪽 vector를 열로 순회하면 된다.

void print_v_22(const vector<vector<string>>& v_22) {
    for (const auto& row : v_22) {
        for (const auto& value : row) {
            cout << value << " ";
        }
        cout << endl;
    }
}




print_v_11(v_11);
print_v_22(v_22);

Comments

댓글을 불러오고 있습니다.