서의 공간

vector::resize()와 vector::reserve() 차이 본문

C++/정보

vector::resize()와 vector::reserve() 차이

홍서의 2020. 12. 12. 18:47

The two functions do vastly different things

The resize() method (and passing argument to constructor is equivalent to that) will insert or delete appropriate number of elements to the vector to make it given size (it has optional second argument to specify their value). It will affect the size(), iteration will go over all those elements, push_back will insert after them and you can directly access them using the operator[].

The reserve() method only allocates memory, but leaves it uninitialized. It only affects capacity(), but size() will be unchanged. There is no value for the objects, because nothing is added to the vector. If you then insert the elements, no reallocation will happen, because it was done in advance, but that's the only effect.

So it depends on what you want. If you want an array of 1000 default items, use resize(). If you want an array to which you expect to insert 1000 items and want to avoid a couple of allocations, use reserve().

 

구글 번역:

두 기능은 크게 다른 일을 합니다!

resize () 메서드 (그리고 생성자에 인수를 전달하는 것은 그와 동일함)는 벡터에 적절한 수의 요소를 삽입하거나 삭제하여 주어진 크기로 만듭니다 (값을 지정하는 선택적 두 번째 인수가 있음). 그것은 size ()에 영향을 미칠 것이고, 반복은 그 모든 요소를 ​​지나갈 것이고, push_back은 그것들 뒤에 삽입될 것이고, operator []를 사용하여 직접 접근할 수 있습니다.

reserve () 메서드는 메모리만 할당하지만 초기화되지 않은 상태로 둡니다. capacity ()에만 영향을 주지만 size ()는 변경되지 않습니다. 벡터에 아무것도 추가되지 않기 때문에 객체에 대한 값이 없습니다. 그런 다음 요소를 삽입하면 사전에 수행되었으므로 재 할당이 발생하지 않지만 그게 유일한 효과입니다.

그래서 그것은 당신이 원하는 것에 달려 있습니다. 1000 개의 기본 항목 배열을 원하면 resize ()를 사용하십시오. 1000 개의 항목을 삽입할 것으로 예상하고 몇 가지 할당을 피하려면 reserve ()를 사용하십시오.

 

출처: vector :: resize ()와 vector :: reserve () 중에서 선택 (qastack.kr)

'C++ > 정보' 카테고리의 다른 글

optional 예제  (0) 2021.02.03
클래스에 대해  (0) 2021.02.03
c++ 함수안에 함수 정의  (0) 2021.01.19
std::vector::erase(), std::vector::clear(), std::remove()  (0) 2020.12.16
C++용 XML 설명서  (0) 2020.12.13
Comments