프로그래밍/C++

[C++] Vector copy constructor의 깊은 복사 여부

EVEerNew 2023. 7. 4. 16:35
반응형

 

C++에서 Vector를 생성할 때 일일이 복사해 주거나 copy 메서드 혹은 assign 메서드를 활용할 수 있지만,

생성 시에 값을 복사해 주는 방법으로 복사 생성자(copy constructor)가 존재한다.

 

이는 복사 대상 Vector의 iterator를 활용하면 설정한 시작(first)과 끝(last)까지 순서대로 복사시켜 새로운 vector를 만들어준다.

 

vector<T> copyVector(first, last);

 

 

void copyCheck() {
        vector<int> vec = {1,2,3,4,5,6 };
        vector<int> subCopyVec(vec.begin() +1 , vec.begin() + 4);
        
        for (auto it = subCopyVec.begin(); it!= subCopyVec.end(); it++) {
            *it = (*it) * -1;
        }

        for (auto it = vec.begin(); it != vec.end(); it++) {
            cout << *it << '\n';
        }

        cout << "\ncopyVector" << '\n';
        for (auto it = subCopyVec.begin(); it != subCopyVec.end(); it++) {
            cout << *it << '\n';
        }
}

 

 

결과

1 2 3 4 5 6

copyVector
-2 -3 -4

 

 

이때의 값들이 주소를 매개로 하는 얕은 복사를 진행하는 줄 알았지만, 결과를 보면 값을 그대로 복사해 주는 깊은 복사이다.

 

 

 

 

 

 

참고

https://cplusplus.com/reference/vector/vector/vector/

 

https://cplusplus.com/reference/vector/vector/vector/

fill (2)explicit vector (size_type n, const allocator_type& alloc = allocator_type()); vector (size_type n, const value_type& val, const allocator_type& alloc = allocator_type());

cplusplus.com

 

반응형