프로필사진

Go, Vantage point

가까운 곳을 걷지 않고 서는 먼 곳을 갈 수 없다.


Github | https://github.com/overnew/

Blog | https://everenew.tistory.com/





티스토리 뷰

반응형

 

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

 

반응형
댓글
반응형
인기글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함