CS/자료구조 & 알고리즘

[C++] vector resize 시 주의할 점

ShovelingLife 2023. 11. 22. 17:29

기존보다 더 작게 할당하게 될 경우 만약 1 라는 값을 5 개 가진 벡터를 3 의 크기로 resizing 하며 2 로 채운다면

#include<iostream>
#include<vector>

using namespace std;

void Print_Vec(const vector<int> vec) {
	for (auto const &it : vec) {
		cout << it << " ";
	}
	cout << "\n";
}

int main() {
	vector<int> vec(5, 1);
	Print_Vec(vec);

	vec.resize(10, 2);
	Print_Vec(vec);

	vec.resize(3, 3);
	Print_Vec(vec);

	return 0;
}

 

결과) 

1 1 1 1 1
1 1 1 1 1 2 2 2 2 2
1 1 1

 

출처