STL 컨테이너를 어떻게 복사합니까?C++ : 컨테이너를 효율적으로 복사하십시오.
// big containers of POD
container_type<pod_type> source;
container_type<pod_type> destination
// case 1
destination = source;
// case 2
destination.assign(source.begin(), source.end());
// case 3 assumes that destination.size() >= source.size()
copy(source.begin(), source.end(), destination.size());
가능한 경우 사례 1을 사용합니다. 케이스 2는 다른 유형의 컨테이너 용입니다. 사례 3은 대상이 원본보다 크고 나머지 요소를 유지하려는 경우에 필요합니다.
그러나 건설/파괴 비용이 0이 아닌 비 POD 요소는 어떻습니까? 케이스 3이 케이스 2보다 좋을까요? 목적지가 소스보다 큰 경우, 구현은 예기치 않은 일을 할 수 있습니다. Visual Studio 2008이 경우 2에서 수행하는 작업입니다.
- 대상의 모든 요소가 삭제됩니다.
- 그런 다음 복사 생성자가 대상의 크기만큼 호출됩니다. 왜?
- 소스의 모든 요소는 대상의 해당 요소에 할당됩니다.
- 대상의 추가 요소가 삭제됩니다.
GCC 4.5가 더 좋습니다. 소스의 모든 요소는 할당을 통해 복사 된 다음 대상의 추가 요소가 삭제됩니다. case3을 사용하여 크기가 인 경우 두 플랫폼 모두에서 동일한 작업을 수행합니다 (크기가 인 기본 생성자 하나만 제외). 제가 의미하는 바를 보여주는 장난감 프로그램이 있습니다.
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
struct A {
A() { cout << "A()\n"; }
A(const A&) { cout << "A(const A&)\n"; }
A& operator=(const A&) {
cout << "operator=\n";
return *this;
}
~A() { cout << "~A()\n"; }
};
int main() {
list<A> source(2);
vector<A> desrination1(3);
vector<A> desrination2(3);
cout << "Use assign method\n";
desrination1.assign(source.begin(), source.end());
cout << "Use copy algorithm\n";
copy(source.begin(), source.end(), desrination2.begin());
desrination2.resize(2);
cout << "The End" << endl;
return 0;
}
무엇이 문제입니까? – onof
나는 거의 자신의 코드로 컨테이너를 복사하지 않는다. (그렇게해야 할 것 같지 않다.) 그래서 나는 결코 그 문제를 결코 고려하지 않았다. –
@onof STL 컨테이너는 어떻게 복사합니까? – user401947