C++의 vector는 동적 배열처럼 동작하는 컨테이너로, 요소가 삽입되거나 삭제될 때 크기를 자동으로 조절합니다. 내부 저장 공간 역시 컨테이너가 알아서 관리해 주기 때문에 개발자가 직접 메모리를 관리할 필요가 없습니다.
그렇다면 resize()와 reserve()는 어떤 점이 다를까요? 핵심적인 차이는 resize()는 벡터의 실제 크기(size)를 변경하지만, reserve()는 크기를 전혀 변경하지 않는다는 점입니다. reserve()는 메모리를 재할당(reallocate)하지 않고도 최소한 지정한 개수만큼의 요소를 담을 수 있도록 용량(capacity)을 미리 확보하는 역할만 합니다. 반면 resize()에 지정한 값이 현재 요소 개수보다 작다면, 벡터는 메모리 크기를 줄이고 초과된 공간을 삭제합니다.
vector::resize()란?
vector::resize()는 벡터의 크기를 지정한 개수로 변경하는 함수입니다.
- 현재 크기보다 큰 값을 전달하면, 부족한 만큼 기본값으로 초기화된 요소가 뒤에 추가됩니다.
- 현재 크기보다 작은 값을 전달하면, 초과된 요소들이 삭제됩니다.
- 두 번째 인자로 값을 함께 전달하면, 새로 추가되는 요소가 해당 값으로 채워집니다.
예제 코드
아래 예제는 메뉴 방식으로 동작하는 프로그램입니다. 사용자는 벡터 크기 확인, 요소 삽입, 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;
}실행 결과
1.Size of the Vector 2.Insert Element into the Vector 3.Resize the vector 4.Display by Iterator 5.Exit Enter your Choice: 1 Size of Vector: 0 1.Size of the Vector 2.Insert Element into the Vector 3.Resize the vector 4.Display by Iterator 5.Exit Enter your Choice: 2 Enter value to be inserted: 1 1.Size of the Vector 2.Insert Element into the Vector 3.Resize the vector 4.Display by Iterator 5.Exit Enter your Choice: 2 Enter value to be inserted: 2 1.Size of the Vector 2.Insert Element into the Vector 3.Resize the vector 4.Display by Iterator 5.Exit Enter your Choice: 2 Enter value to be inserted: 4 1.Size of the Vector 2.Insert Element into the Vector 3.Resize the vector 4.Display by Iterator 5.Exit Enter your Choice: 2 Enter value to be inserted: 5 1.Size of the Vector 2.Insert Element into the Vector 3.Resize the vector 4.Display by Iterator 5.Exit Enter your Choice: 2 Enter value to be inserted: 5 1.Size of the Vector 2.Insert Element into the Vector 3.Resize the vector 4.Display by Iterator 5.Exit Enter your Choice: 4 Displaying Vector by Iterator: 1 2 4 5 5 1.Size of the Vector 2.Insert Element into the Vector 3.Resize the vector 4.Display by Iterator 5.Exit Enter your Choice: 3 Resize the vector elements: 1.Size of the Vector 2.Insert Element into the Vector 3.Resize the vector 4.Display by Iterator 5.Exit Enter your Choice: 4 Displaying Vector by Iterator: 1 2 4 5 1.Size of the Vector 2.Insert Element into the Vector 3.Resize the vector 4.Display by Iterator 5.Exit Enter your Choice: 5
실행 결과를 보면, 요소 5개(1, 2, 4, 5, 5)를 삽입한 뒤 v.resize(4)를 호출하자 마지막 요소가 잘려나가면서 벡터의 크기가 4로 줄어든 것을 확인할 수 있습니다. 이처럼 resize()는 벡터가 실제로 보유한 데이터 개수 자체를 변경합니다.
vector::reserve()란?
vector::reserve()는 벡터가 메모리를 재할당하지 않고도 최소한 지정한 개수만큼의 요소를 저장할 수 있도록 미리 공간을 확보하라고 컨테이너에 알려주는 함수입니다.
즉, reserve()는 size에는 아무런 영향을 주지 않으며 오직 capacity만 늘립니다. 이후 push_back()으로 요소를 계속 추가할 때 발생할 수 있는 불필요한 메모리 재할당과 복사 비용을 줄여, 프로그램의 성능을 최적화하는 용도로 활용됩니다. 참고로 전달한 값이 max_size()를 초과하면 length_error 예외가 발생할 수 있습니다.
예제 코드
#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;
}실행 결과
1.Size of the Vector 2.Insert Element into the Vector 3.Reserve the vector 4.Display by Iterator 5.Exit Enter your Choice: 1 Size of Vector: 0 1.Size of the Vector 2.Insert Element into the Vector 3.Reserve the vector 4.Display by Iterator 5.Exit Enter your Choice: 2 Enter value to be inserted: 1 1.Size of the Vector 2.Insert Element into the Vector 3.Reserve the vector 4.Display by Iterator 5.Exit Enter your Choice: 2 Enter value to be inserted: 2 1.Size of the Vector 2.Insert Element into the Vector 3.Reserve the vector 4.Display by Iterator 5.Exit Enter your Choice: 2 Enter value to be inserted: 3 1.Size of the Vector 2.Insert Element into the Vector 3.Reserve the vector 4.Display by Iterator 5.Exit Enter your Choice: 2 Enter value to be inserted: 4 1.Size of the Vector 2.Insert Element into the Vector 3.Reserve the vector 4.Display by Iterator 5.Exit Enter your Choice: 2 Enter value to be inserted: 5 1.Size of the Vector 2.Insert Element into the Vector 3.Reserve the vector 4.Display by Iterator 5.Exit Enter your Choice: 3 Reserve the vector elements: 1.Size of the Vector 2.Insert Element into the Vector 3.Reserve the vector 4.Display by Iterator 5.Exit Enter your Choice: 4 Displaying Vector by Iterator: 1 2 3 4 5 1.Size of the Vector 2.Insert Element into the Vector 3.Reserve the vector 4.Display by Iterator 5.Exit Enter your Choice: 4 Displaying Vector by Iterator: 1 2 3 4 5 1.Size of the Vector 2.Insert Element into the Vector 3.Reserve the vector 4.Display by Iterator 5.Exit
출력에서 확인할 수 있듯이 v.reserve(100)를 호출한 이후에도 size는 여전히 5이며, 화면에 표시되는 요소 목록도 전혀 변하지 않았습니다. 이는 reserve()가 실제 데이터가 아니라 저장 용량만 확보하기 때문입니다. 확보된 용량은 v.capacity()로 직접 확인해 볼 수 있습니다.
resize() vs reserve() 비교 정리
| 구분 | resize() | reserve() |
|---|---|---|
| 변경 대상 | size(실제 요소 개수) | capacity(저장 용량) |
| 요소 생성/삭제 | 새 요소를 추가하거나 기존 요소를 삭제함 | 요소를 생성하거나 삭제하지 않음 |
| size() 반환값 | 호출 후 변경됨 | 변화 없음 |
| 주요 용도 | 벡터의 크기를 실제로 조정 | 재할당 최소화를 통한 성능 최적화 |
| 비고 | 두 번째 인자로 새 요소의 초기값 지정 가능 | n이 max_size()를 초과하면 length_error 발생 가능 |
마무리
정리하면, 벡터에 담긴 실제 데이터 개수를 늘리거나 줄이고 싶다면 resize()를 사용하고, 앞으로 많은 요소가 추가될 것을 대비해 메모리 재할당 비용을 줄이고 싶다면 reserve()를 사용하는 것이 좋습니다. 두 함수의 역할 차이를 정확히 이해하고 있으면, C++에서 벡터를 훨씬 효율적으로 활용할 수 있습니다.