Computer >> 컴퓨터 >  >> 프로그래밍 >> C++

C++ std::vector::resize()와 std::vector::reserve()의 차이점 완벽 비교

C++의 std::vector는 동적 배열처럼 동작하며, 요소가 삽입되거나 삭제될 때 컨테이너가 저장 공간을 자동으로 관리합니다. 하지만 많은 개발자가 혼동하는 부분이 바로 resize()reserve()의 차이입니다.

핵심 차이를 먼저 요약하면 다음과 같습니다.

  • resize(): 벡터의 실제 크기(size)를 변경합니다. 지정한 값이 현재 크기보다 작으면 초과분의 메모리를 해제하고 요소를 삭제합니다.
  • reserve(): 벡터의 실제 크기는 그대로 두고, 최소한 지정한 개수만큼의 요소를 담을 수 있도록 용량(capacity)만 미리 확보합니다. 메모리 재할당(reallocation) 없이 효율적으로 공간을 예약하는 용도입니다.

vector::resize()란?

resize()는 벡터의 크기를 직접 변경하는 함수입니다. 크기를 늘릴 경우 새로 추가되는 요소는 기본값(0 등)으로 초기화되며, 줄일 경우 뒤쪽의 요소들이 삭제됩니다.

예제 코드 (resize)

아래 예제는 메뉴 기반 프로그램으로 벡터의 크기 확인, 요소 삽입, 크기 조정, 반복자 출력 기능을 수행합니다.

#include <iostream>
#include <vector>
using namespace std;
int main() {
    vector<int> v;
    vector<int>::iterator it;
    int c, i;
    while (1) {
        cout<<"1.Size of the Vector"<<endl;
        cout<<"2.Insert Element into the Vector"<<endl;
        cout<<"3.Resize the vector"<<endl;
        cout<<"4.Display by Iterator"<<endl;
        cout<<"5.Exit"<<endl;
        cout<<"Enter your Choice: ";
        cin>>c;
        switch(c) {
            case 1:
                cout<<"Size of Vector: ";
                cout<<v.size()<<endl; // 벡터의 크기 출력
                break;
            case 2:
                cout<<"Enter value to be inserted: ";
                cin>>i;
                v.push_back(i); // 값 삽입
                break;
            case 3:
                cout<<"Resize the vector elements:"<<endl;
                v.resize(4); // 벡터 크기를 4로 조정
                break;
            case 4:
                cout<<"Displaying Vector by Iterator: ";
                for (it = v.begin(); it != v.end(); it++) { // 모든 값 출력
                    cout<<*it<<" ";
                }
                cout<<endl;
                break;
            case 5:
                exit(1);
                break;
            default:
                cout<<"Wrong Choice"<<endl;
        }
    }
    return 0;
}

실행 결과

Enter your Choice: 2
Enter value to be inserted: 1
... (1, 2, 4, 5, 5 순서로 5개 삽입)
Enter your Choice: 4
Displaying Vector by Iterator: 1 2 4 5 5
Enter your Choice: 3
Resize the vector elements:
Enter your Choice: 4
Displaying Vector by Iterator: 1 2 4 5

위 결과에서 확인할 수 있듯이, 5개의 요소를 가진 벡터에 v.resize(4)를 호출하면 마지막 요소가 삭제되어 크기가 4로 줄어듭니다. 이것이 resize()의 핵심 동작 방식입니다.

vector::reserve()란?

reserve()는 벡터가 최소한 지정된 개수만큼의 요소를 저장할 수 있도록 메모리를 미리 할당하지만, 실제 크기(size)는 변경하지 않습니다. 즉, size() 값은 그대로 유지되며 capacity()만 늘어납니다.

예제 코드 (reserve)

#include <iostream>
#include <vector>
using namespace std;
int main() {
    vector<int> v;
    vector<int>::iterator it;
    int c, i;
    while (1) {
        cout<<"1.Size of the Vector"<<endl;
        cout<<"2.Insert Element into the Vector"<<endl;
        cout<<"3.Reserve the vector"<<endl;
        cout<<"4.Display by Iterator"<<endl;
        cout<<"5.Exit"<<endl;
        cout<<"Enter your Choice: ";
        cin>>c;
        switch(c) {
            case 1:
                cout<<"Size of Vector: ";
                cout<<v.size()<<endl;
                break;
            case 2:
                cout<<"Enter value to be inserted: ";
                cin>>i;
                v.push_back(i);
                break;
            case 3:
                cout<<"Reserve the vector elements."<<endl;
                v.reserve(100); // 100개 요소 공간 미리 확보
                break;
            case 4:
                cout<<"Displaying Vector by Iterator: ";
                for (it = v.begin(); it != v.end(); it++) {
                    cout<<*it<<" ";
                }
                cout<<endl;
                break;
            case 5:
                exit(1);
                break;
            default:
                cout<<"Wrong Choice"<<endl;
        }
    }
    return 0;
}

실행 결과

Enter your Choice: 2
Enter value to be inserted: 1
... (1, 2, 3, 4, 5 순서로 5개 삽입)
Enter your Choice: 3
Reserve the vector elements.
Enter your Choice: 4
Displaying Vector by Iterator: 1 2 3 4 5

v.reserve(100)를 호출한 후에도 반복자로 출력해 보면 여전히 5개의 요소만 존재합니다. 이처럼 reserve()는 실제 데이터에는 아무런 영향을 주지 않고, 향후 push_back() 호출 시 발생할 수 있는 불필요한 메모리 재할당과 복사 비용을 줄여 성능을 최적화하는 역할을 합니다.

resize() vs reserve() 한눈에 비교하기

구분resize()reserve()
size() 변화O (변경됨)X (유지됨)
capacity() 변화O (변경될 수 있음)O (지정값 이상으로 확보)
요소 추가/삭제크기 증가 시 기본값 요소 추가, 감소 시 요소 삭제요소 변화 없음
주요 용도벡터의 실제 크기 조절메모리 재할당 방지 및 성능 최적화

정리하면, 실제로 요소를 추가하거나 제거하고 싶다면 resize()를 사용하고, 데이터는 그대로 두고 미래에 들어올 요소를 위한 메모리만 미리 잡아두고 싶다면 reserve()를 사용하는 것이 올바른 선택입니다.